Java NIO on Android: Attempting to READ/WRITE while connection is still pending?

大城市里の小女人 提交于 2020-01-11 12:11:55

问题


This question regards Java's NIO on Android (2.2, though I can build for higher APIs if necessary): After performing a SocketChannel connect() to a destination IP address, I register my channel for a READ operation. The problem is that when I try to perform a READ on the resulting selected key set, I receive NotYetConnectedException. While I can check the channel's status with isConnectionPending before I try to READ, I would ideally like to have READ keys be selected only when the connection is actually working. Any ideas?


回答1:


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:

  1. If it returns true, you must then deregister OP_CONNECT, and you may then register OP_READ or OP_WRITE.

  2. If it returns false, do nothing: the connection is still pending.

  3. If it throws an exception, the connect has failed and you must close the channel.



来源:https://stackoverflow.com/questions/13050848/java-nio-on-android-attempting-to-read-write-while-connection-is-still-pending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!