I am currently using the java.nio.channel.Selectors & SocketChannels for a application that will open 1-to-many connections for continues Streaming to a Server. I have three
The correct way to process OP_CONNECT
is to attempt finishConnect()
once, and if it succeeds deregister OP_CONNECT
and register OP_READ
or OP_WRITE
, probably the latter as you are a client. Looping and sleeping in non-blocking mode doesn't make sense. If finishConnect()
returns false, OP_CONNECT
will fire again.
Your processing of !key.isAcceptable()
, !key.isReadable()
, and !key.isWriteable()
makes absolutely zero sense whatsoever. If the key is acceptable, call accept()
. If it's readable, call read()
. If it's writeable, call write()
. It's as simple as that.
You need to be aware that channels are almost always writeable, except for the brief periods when their socket send buffer is full. So only register for OP_WRITE
when you have something to write, or better still after you've tried a write and got a zero return; then when OP_WRITE
fires, retry the write and deregister OP_WRITE
unless you got another zero.
You are being far too economical with your ByteBuffer
. In practice you need one per channel. You can save it as the key attachment so you can get it back when you need it. Otherwise you don't have any way of accumulating partial reads, which are certain to happen, or any way of retrying writes either.