Reputation: 862
I'm trying to implement a simple client/server program on linux using TCP and the standard socket.h library. server handling multiple clients and each client can close() or shutdown() the socket any time he wants.
on the server side (using a non blocking read):
int nBytes;
if ((nBytes = recv(socket, buffer, BUFFER_SIZE, MSG_DONTWAIT)) == -1)
{
if (errno != EAGAIN && errno != EWOULDBLOCK)
{
//print to log
}
}
if (nBytes == 0)
{
//other side closed the connection
}
I'm getting recv() returning -1 and error set to ECONNRESET. If the client has closed the connection shouldn't recv() return 0?
Upvotes: 3
Views: 7913
Reputation: 180286
If the remote peer has cleanly closed the connection, and there are no more bytes waiting to be read on the local end, then yes, recv()
should return 0
. So if you get an ECONNRESET
then it's reasonable to assume that an orderly closure is not what has happened.
An ECONNRESET
often indicates that the remote peer sent a RST packet without having first closed the connection cleanly. There are many reasons why this might happen. Alternatively, as EJP observed, a reset may originate locally, too.
In any event, after an ECONNRESET
it's not reasonable to suppose that you will be able to read anything further from the socket, so in your particular case you should probably handle it much the same as way as you handle recv()
returning 0
, +/- logging.
Upvotes: 4
Reputation: 310936
There are numerous causes, including but not limited to:
This is a fatal error, and you should close the socket when you get it.
each client can
close()
orshutdown()
the socket any time he wants.
No he can't. See above.
Upvotes: 11
Reputation: 3452
You may get ECONNRESET if client closed his side without reading sent data. If he closed connection properly you'll get 0.
Upvotes: 3