Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO connect to socket

Tags:

java

nio

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?

like image 639
Asaf Nevo Avatar asked Dec 10 '25 13:12

Asaf Nevo


1 Answers

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.

like image 190
user207421 Avatar answered Dec 12 '25 02:12

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!