Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving data from already closed socket?

Suppose I have a server application - the connection is over TCP, using UNIX sockets.

The connection is asynchronous - in other words, clients' and servers' sockets are non-blocking.

Suppose the following situation: in some conditions, the server may decide to send some data to a connected client and immediately close the connection: using shutdown with SHUT_RDWR.

So, my question is - is it guaranteed, that when the client call recv, it will receive the (sent by the server) data?

Or, to receive the data, recv must be called before the server's shutdown? If so, what should I do (or, to be more precise, how should I do this), to make sure, that the data is received by the client?

like image 320
Kiril Kirov Avatar asked Aug 09 '12 18:08

Kiril Kirov


People also ask

What happens if socket is closed?

close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.

Can reuse a closed TCP sockets?

You cannot reuse the actual socket -- it's the endpoint of a dead connection. You can re-use the socket handle. Once you call close , regardless of what happens to the actual socket, the handle can be reused.

Can you read and write from the same socket?

Sockets are full duplex, so you can read while you write and vice-versa.

How do you know if a socket has been closed?

The most obvious way to accomplish this is having that process call read on the socket for a connection and check whether read returns 0 (i.e. reads zero bytes from the socket), in which case we know that the connection has been closed.


1 Answers

You can control this behavior with "setsockopt(SO_LINGER)":

  • man setsockopt

SO_LINGER Waits to complete the close function if data is present. When this option is enabled and there is unsent data present when the close function is called, the calling application is blocked during the close function until the data is transmitted or the connection has timed out. The close function returns without blocking the caller. This option has meaning only for stream sockets.

See also:

  • man read

  • Beej's Guide to Network Programming

like image 149
paulsm4 Avatar answered Oct 01 '22 18:10

paulsm4