views:

331

answers:

1

I am creating socket server. But I do not know, How I can know client disconnected or not? I am creating server under Windows and using berkeley sockets function (read, send, connect....). Preferably I want a cross-platfomennoe solution (without WSA functions).

I can write to socket 0 byte and ckeck error. But it is not good solution.

+4  A: 

When a client disconnects, you'll get a "read" event but the read() will return 0.

ssize_t bytes_read;
if ((bytes_read = read(...)) == 0)
{
    // client disconnected
}
else if (bytes_read == -1)
{
    // some sort of error (also no data available when using non-blocking sockets).
}
else
{
    // you have bytes_reads bytes to process
}
R Samuel Klatchko
You're right to point out EAGAIN, but there's also EINTR, which means your process got a signal while reading. I usually handle both of these.
asveikau
Also he mentioned he's using Windows, so he needs to use recv() instead of read().
asveikau