Java NIO - using Selectors

。_饼干妹妹 提交于 2019-12-06 09:25:45

a Server socket channel is registered to listen for accept, when accepted a channel is registered for read and once read it is registered for write. How does it then go back into listening for an accept?

It doesn't have to 'go back'. It's listening. It's registered. Nothing has changed.

What happens if a channel is registered twice?

The interestOps are updated and the previous key attachment is lost.

I mean - in the above example, a socket is registered for write every time after a message is read.

It's a very poor example. Incorrect technique. You should just write. If write() returns zero, then you should (a) register the channel for OP_WRITE; (b) retry the write when the channel becomes writable; and (c) deregister the channel for OP_WRITE once the write has completed.

I guess this assumes that the connection will then be closed after writing.

I don't see why. It doesn't follow. In any case it's a poor example, not to be imitated. You would be better off imitating answers here, rather than unanswered questions.

What happens if you want to maintain an open connection and at different intervals write to the socket - must you register an interestOp each time? Is it harmful to register the same channel twice?

See above. Keep the channel open. Its interestOps won't change unless you change them; and you should handle writing as above, not as per the poor example you cited.

Multithreading: What is the best design now for writing a multithreaded server - as the above non blocking approach assumes that one thread can handle writing and reading.

If you want multi-threading, use blocking I/O, most simply via java.net. If you want non-blocking I/O you don't need multi-threading. I don't understand why you're asking about both in the same question.

Should you create a new thread if the read/write operation is expected to take a while?

In the most general case of blocking I/O you have two threads per connection: one for reading and one for writing.

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