Mischiefblog
I make apps for other people

Detecting disconnected sockets when reading

Posted by Chris Jones
On August 10th, 2005 at 15:49

Permalink | Trackback | Links In |

Comments Off on Detecting disconnected sockets when reading
Posted in Java, Python, Tech

Detecting disconnected sockets in Python (and C)
# read from the client socket
try:
    msg = reader.recv(NetServer.max_message_length)
 
    if len(msg) == 0:
        # socket closed
        self.shutdown_client_socket(reader)
        NetServer.logger.info('Connection ' +
             str(reader.getpeername()) + ' closed.')
    else:
        # pass the message to the client to handle it
        self.clients[cli_sock].read_message(msg)
except socket.error, err:
    NetServer.logger.error('recv() error')
    # kill the client
    self.shutdown_client_socket(reader)

When I detect that 0 bytes were read from a readable socket, assume that the socket was closed.

Detecting disconnected sockets using Java NIO
if (key.isReadable()) {
    // get the readable channel
    channelClient = (SocketChannel)key.channel();
 
    // get the client
    client = hmClients.get(channelClient);
 
    if (client != null) {
        // read into the client's input buffer
        try {
            msgSize = channelClient.read(bb);
 
            if (msgSize < 0) {                 log.info("Client " + client + " disconnected.");                 shutdownClient(channelClient, client);             } else {                 bb.flip();                 bMsg = new byte[msgSize];                 bb.get(bMsg);                 client.acceptMessage(bMsg);                 bb.clear();             }         } catch (IOException e) {             log.warn("Can't read from " + client + ". Disconnecting.");             // disconnect the client             shutdownClient(channelClient, client);         }     } else {         // the key is probably being removed         // from the selector         log.warn("Got output for a disconnected client from "             + channelClient.socket().getRemoteSocketAddress() + ".");         }     } }

I tried to use exceptions to capture the disconnected socket, but that didn't work. Taking the advice of netizens, I attempted to look for -1 or anything less than 0. If you read directly into the ByteBuffer and use the position() method to get the bytes read (instead of the return value of read()), you’ll need to test for zero-length byte arrays instead of -1, which indicates a read error (or closed file handle).

Comments are closed.