writing to sockets

A

Andersen

In non-blocking NIO, why do I need the OP_WRITE flag to be set in an
interest set ever? I understand that OP_READ indicates that new data is
ready to be read. But for writing, should I not only need to do
Channel.write(buffer) whenever I feel for it?
 
S

Stefan Schulz

In nonblocking mode, if the write buffer of the socket is full, just
"blasting away" with writes will cause a large number of zero-length
writes. If inside a tight loop, you would effectively busy-wait for
sending of data, which would clear some of the buffer (much like not
looking at a selector, and just calling read() repeatedly would
busy-wait for arrival of data).
 
A

Andersen

Gotcha, so I can have my data (can be huge) stored into Collections,
then when WRITE is ready, move it over to a ByteBuffer and output to the
channel. That is the best strategy?

The reason I am having the Collections is that I want to have a per
connection buffer (for simple design), if I would allocate big
ByteBuffers for each connection, that would give me memory problems when
I have many connections (a few thousands). So Collections resize
nicely, then use ByteBuffers and feed the channel...
 
A

Andersen

Page 134 of Java NIO (Ron Hitchens, O'Reilly) calls sayHello(channel)
which does write without checking for readiness. Is this bad programming
style?
 
S

Stefan Schulz

Well, that depends: If the channel is in blocking mode, the call is
just fine. If however, the call is made in nonblocking mode, only part
of the data (possibly none) might be written, which is not a good thing.
 
G

Gordon Beaton

In non-blocking NIO, why do I need the OP_WRITE flag to be set in an
interest set ever? I understand that OP_READ indicates that new data
is ready to be read. But for writing, should I not only need to do
Channel.write(buffer) whenever I feel for it?

You can write without OP_WRITE as long as write() succeeds. When
write() returns 0, wait until OP_WRITE is indicated before attempting
to write again.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,786
Messages
2,569,626
Members
45,325
Latest member
31Rolly51

Latest Threads

Top