NIO: send a message and then disconnect immediately

In some cases, I want to send an error message from the server to the client using non-blocking input-output ( SocketChannel.write(ByteBuffer)), and then disconnect the client. Assuming that I write the full contents of the message and then immediately disconnect, I assume that the client may not receive this message, since I assume that the OS did not actually send data at the moment.

Is this correct, and if there is a recommended approach to solving this situation?

I was thinking about using a timer in which if I want to disconnect a client, I send a message and then close it after 1-2 seconds.

+3
source share
3 answers

SocketChannel.write will in non-blocking mode return the number of bytes that can be immediately sent to the network without blocking. Your question makes me think that you expect the write method to consume the entire buffer and try to send additional data asynchronously to the network, but that’s not how it works.

If you really need to make sure that an error message is sent to the client before disconnecting the socket, I would simply enable the lock before calling the write method. Using non-blocking mode, you have to call the record in a loop, counting the number of bytes sent by each call, and exit the loop when you manage to send the entire message to the socket (a bad decision, I know, unnecessary code, waiting for waiting, etc.) .

+1

. async api " , " .

0

The socket method close()ensures that everything sent using write before is actually sent before the socket is really closed. However, this assumes that yours write()was able to copy all the data into the tcp stacks output window, which will not always work. To resolve this issue, see Other Answers.

0
source

Source: https://habr.com/ru/post/1731201/


All Articles