public SelectionKey accept(Selector selector, SocketChannel socketChannel) throws IOException {
    writeBuffer.clear();
    readBuffer.clear();
    readBuffer.flip();
    currentObjectLength = 0;
    try {
      this.socketChannel = socketChannel;
      socketChannel.configureBlocking(false);
      Socket socket = socketChannel.socket();
      socket.setTcpNoDelay(true);

      selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);

      if (DEBUG) {
        debug(
            "kryonet",
            "Port "
                + socketChannel.socket().getLocalPort()
                + "/TCP connected to: "
                + socketChannel.socket().getRemoteSocketAddress());
      }

      lastReadTime = lastWriteTime = System.currentTimeMillis();

      return selectionKey;
    } catch (IOException ex) {
      close();
      throw ex;
    }
  }
Example #2
0
 public void close() {
   boolean wasConnected = isConnected;
   isConnected = false;
   tcp.close();
   if (udp != null && udp.connectedAddress != null) udp.close();
   if (wasConnected) {
     notifyDisconnected();
     if (INFO) info("kryonet", this + " disconnected.");
   }
   setConnected(false);
 }
  public void connect(Selector selector, SocketAddress remoteAddress, int timeout)
      throws IOException {
    close();
    writeBuffer.clear();
    readBuffer.clear();
    readBuffer.flip();
    currentObjectLength = 0;
    try {
      SocketChannel socketChannel = selector.provider().openSocketChannel();
      Socket socket = socketChannel.socket();
      socket.setTcpNoDelay(true);
      // socket.setTrafficClass(IPTOS_LOWDELAY);
      socket.connect(remoteAddress, timeout); // Connect using blocking mode for simplicity.
      socketChannel.configureBlocking(false);
      this.socketChannel = socketChannel;

      selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);
      selectionKey.attach(this);

      if (DEBUG) {
        debug(
            "kryonet",
            "Port "
                + socketChannel.socket().getLocalPort()
                + "/TCP connected to: "
                + socketChannel.socket().getRemoteSocketAddress());
      }

      lastReadTime = lastWriteTime = System.currentTimeMillis();
    } catch (IOException ex) {
      close();
      IOException ioEx = new IOException("Unable to connect to: " + remoteAddress);
      ioEx.initCause(ex);
      throw ioEx;
    }
  }