java.nio Selectors and SocketChannel for continues Streaming

前端 未结 1 523
庸人自扰
庸人自扰 2021-02-06 10:11

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

相关标签:
1条回答
  • 2021-02-06 10:39
    1. 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.

    2. 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.

    3. 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.

    4. 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.

    0 讨论(0)
提交回复
热议问题