Java NIO connect to socket

后端 未结 2 820
予麋鹿
予麋鹿 2021-01-07 11:56

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

@Override
public void run() {
    try {
        address = new InetSocketAddr         


        
相关标签:
2条回答
  • 2021-01-07 12:09

    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.

    0 讨论(0)
  • 2021-01-07 12:17

    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

    0 讨论(0)
提交回复
热议问题