Java NIO SocketChannel writing problem

I am using Java NIO SocketChannel to write: int n = socketChannel.write(byteBuffer);

In most cases, data is sent in one or two parts; that is, if the data cannot be sent to one passport, the remaining data will be repeated.

The problem here is that sometimes the data is not sent completely in one attempt, the rest of the data when you try to send several times, it happens that even after several attempts, not a single character is written to the channel, finally, after a while, correcting data is sent ... This data may not be large, it may be about 2000 characters.

What could be the reason for this behavior? Could external factors like RAM, OS, etc. cause Hindian?

Please help me to solve this problem. If any other information is required, please let me know. Thanks to

EDIT:

Is there a way in the NIO SocketChannel to check if the channel can be stuffed with data to write before actually recording. The goal is that after attempting to write complete data, if some data has not been written to the channel, before writing the remaining data, we can check if the SocketChannel can receive more data; so instead of trying repeatedly fruitlessly, the thread responsible for writing this data can wait or do something else.

+2


a source to share


2 answers


TCP / IP is a streaming protocol. At any level, there is no guarantee that the data you send will not be split into single-byte segments, or anything in between and one segment, as you wrote it.

Your expectations are misplaced.



Return your EDIT, write () will return zero when the socket send buffer is full. When you get this, register a channel for OP_WRITE and stop the write cycle. When you receive OP_WRITE, deregister (very important) and keep writing. If write () returns zero again, retry.

+1


a source


When using TCP, we can only write on the sender socket pipe until the socket buffers are full, not after that. Thus, in case the receiver is slowly consuming data, the socket buffers on the sender's side fill up and, as you mentioned, write () can return zero.



Anyway, when on the sender side some data is sent, we have to register the SocketChannel with the selector with OP_WRITE as the operation concerned, and when the selector returns SelectionKey, check key.isWritable () and try writing on that channel. As Nilesh mentioned above, remember to unregister the OP_WRITE bits with the selector after writing the complete data.

+1


a source







All Articles