コード例 #1
0
  private void handle(SelectionKey key) throws IOException {
    // TODO Auto-generated method stub

    ServerSocketChannel server = null;
    SocketChannel client = null;
    String receiveText = null;
    int count = 0;

    if (key.isAcceptable()) {
      // client require accept events
      server = (ServerSocketChannel) key.channel();
      client = server.accept();
      client.configureBlocking(false);
      client.register(selector, SelectionKey.OP_READ);
    } else if (key.isReadable()) {
      // 如果是read事件,则直接读取
      client = (SocketChannel) key.channel();
      recBuffer.clear();
      count = client.read(recBuffer);
      if (count > 0) {
        recBuffer.flip();
        receiveText = decode.decode(recBuffer.asReadOnlyBuffer()).toString();
        System.out.println(client.toString() + ":" + receiveText);
        sendBuffer.clear();
        sendBuffer.put((sdf.format(new Date()) + "服务器收到你的消息").getBytes());
        sendBuffer.flip();
        client.write(sendBuffer);
        dispatch(client, receiveText);
        client = (SocketChannel) key.channel();
        client.register(selector, SelectionKey.OP_READ);
      }
    }
  }
コード例 #2
0
  protected void handleListenEvent(SelectionKey key, ServerSocketChannel ssc) throws IOException {
    SocketChannel sock = listenSock.accept();
    log.info("Switch connected from {}", sock.toString());
    sock.socket().setTcpNoDelay(this.noDelay);
    sock.configureBlocking(false);
    sock.socket().setSendBufferSize(1024 * 1024);
    OFSwitchImpl sw = new OFSwitchImpl();

    // Try to even the # of switches per thread
    // TODO something more intelligent here based on load
    IOLoop sl = null;
    for (IOLoop loop : switchIOLoops) {
      if (sl == null || loop.getStreams().size() < sl.getStreams().size()) sl = loop;
    }

    // register initially with no ops because we need the key to init the stream
    SelectionKey switchKey = sl.registerBlocking(sock, 0, sw);
    OFStream stream = new OFStream(sock, factory, switchKey, sl);
    stream.setImmediate(this.immediate);
    sw.setInputStream(stream);
    sw.setOutputStream(stream);
    sw.setSocketChannel(sock);
    sw.setBeaconProvider(this);
    sw.transitionToState(OFSwitchState.HELLO_SENT);

    addSwitch(sw);

    // Send HELLO
    stream.write(factory.getMessage(OFType.HELLO));

    // register for read
    switchKey.interestOps(SelectionKey.OP_READ);
    sl.addStream(stream);
    log.info("Added switch {} to IOLoop {}", sw, sl);
    sl.wakeup();
  }