Asaf Nevo
Asaf Nevo

Reputation: 11688

Java NIO connect to socket

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?

Upvotes: 2

Views: 9403

Answers (2)

user207421
user207421

Reputation: 311028

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.

Upvotes: 12

Asaf Nevo
Asaf Nevo

Reputation: 11688

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

Upvotes: -1

Related Questions