2

I'm trying to connect to a remote server and send a login message in my Thread:

@Override
public void run() {
    try {
        address = new InetSocketAddress(host, port);
        incomingMessageSelector = Selector.open();
        socketChannel = SocketChannel.open();           
        socketChannel.configureBlocking(false);
        socketChannel.connect(address);
        socketChannel.register(incomingMessageSelector, SelectionKey.OP_READ);
        serverManager.loginToServer();
    }
}

the loginServer() is a method which send a message to ther server but i keep getting an:

java.nio.channels.NotYetConnectedException

how can i check and wait for connection before sending this loginServer() method?

Jonathan
  • 20,053
  • 6
  • 63
  • 70
Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154
  • I would suggest you initially implement using blocking NIO. Its much simpler and may do what you want. Note: In NIO, the default behaviour is blocking. – Peter Lawrey Nov 12 '12 at 16:30

2 Answers2

12

If you're connecting in non-blocking mode you should:

  • register the channel for OP_CONNECT
  • when it fires call finishConnect()
  • if that returns true, deregister OP_CONNECT and register OP_READ or OP_WRITE depending on what you want to do next
  • if it returns false, do nothing, keep selecting
  • if either connect() or finishConnect() throws an exception, close the channel and try again or forget about it or tell the user or whatever is appropriate.

If you don't want to do anything until the channel connects, do the connect in blocking mode and go into non-blocking mode when the connect succeeds.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

i've found an answer.. i should use:

    socketChannel = SocketChannel.open(address);            
    socketChannel.configureBlocking(false);

    while (!socketChannel.finishConnect());

   //my code after connection

because the NIO is in not blocking mode we have to wait until it finish its connection

Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154
  • 4
    This is pointless. Just do the connect in blocking mode and avoid smoking the CPU. Or else register OP_CONNECT and use select() and call finishConnect() when it fires. – user207421 Nov 13 '12 at 03:22