Java NIO连接到套接字 [英] Java NIO connect to socket
本文介绍了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();
}
}
loginServer()是一种发送消息的方法到服务器,但我一直得到:
the loginServer() is a method which send a message to ther server but i keep getting an:
java.nio.channels.NotYetConnectedException
如何在发送此loginServer()方法之前检查并等待连接?
how can i check and wait for connection before sending this loginServer() method?
推荐答案
如果您以非阻止模式连接,您应该:
If you're connecting in non-blocking mode you should:
- 注册
OP_CONNECT
- 当它触发来电
finishConnect()
- 如果返回true,请取消注册
OP_CONNECT
并注册OP_READ
或OP_WRITE
取决于你想做什么 - 如果它返回false,什么都不做,继续选择
- 如果<$ li c $ c> connect()或
finishConnect()
抛出异常,关闭频道并再试一次或忘记它或告诉用户或什么是合适的。
- register the channel for
OP_CONNECT
- when it fires call
finishConnect()
- if that returns true, deregister
OP_CONNECT
and registerOP_READ
orOP_WRITE
depending on what you want to do next - if it returns false, do nothing, keep selecting
- if either
connect()
orfinishConnect()
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.
这篇关于Java NIO连接到套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文