这个问题是关于 Android 上 Java 的 NIO(2.2,虽然我可以在必要时为更高的 API 构建):在对目标 IP 地址执行 SocketChannel connect() 之后,我注册我的通道以进行 READ 操作。问题是当我尝试对生成的选定键集执行 READ 时,我收到 NotYetConnectedException。虽然我可以在尝试 READ 之前使用 isConnectionPending 检查通道的状态,但理想情况下,我希望仅在连接实际工作时才选择 READ 键。有任何想法吗?
问问题
656 次
1 回答
4
You're doing it wrong.
While the connection is pending, the channel must only be registered for OP_CONNECT
.
When OP_CONNECT
fires, you must call finishConnect()
, and then proceed as follows:
If it returns true, you must then deregister
OP_CONNECT
, and you may then registerOP_READ
orOP_WRITE
.If it returns false, do nothing: the connection is still pending.
If it throws an exception, the connect has failed and you must close the channel.
于 2012-10-24T21:06:00.640 回答