Kristian Spangsege
Kristian Spangsege

Reputation: 2973

How to send a message before closing TCP connection [POSIX]

I have a standard client server situation. Clients connect to the server, and the server manages multiple client connections using select() (or similar). Everything uses the POSIX system level networking API.

Sometimes the server needs to close a connection. I want the server to be able to send a message to the client before closing the socket, to inform the client about the reason for the connection being closed.

What is the best way to do that?

The straight forward approach would be to simply have the server write the message and then close (close()), but I imagine that this is problematic, as the client might then get a write error due to the connection having been closed by the server, before the client gets a chance to read the final message written by the server.

Is that the case, or can I be sure that the client does not get a write error until after it has read everything?

Is there a better way to do it?

If possible, I would prefer a solution that is based only on the POSIX specification.

Upvotes: 0

Views: 1043

Answers (1)

David Schwartz
David Schwartz

Reputation: 182893

The server should:

  1. Write the message.
  2. Shut down the write side of the connection with a call to shutdown.
  3. Continue reading from the connection until it detects a normal shutdown so that all data sent by the client is read.

Upvotes: 2

Related Questions