Skip to content
Advertisement

Python – non-blocking sockets using selectors

My Problem in short: I dont know how the selector knows which socket should read or write first.

It is a Server that can handle multi connections and its flow should be:

  1. Server creates listening socket
  2. Client creates 2 sockets and connects them to the server
  3. Client 2 sockets send the messages
  4. Server 2 sockets echo those messages, client and server closing connection

which is what happens, but if the created server sockets would write first, the connection would be closed immediately or throw an exception(?), since it doesn’t even call send and the client socket would recv nothing. So how does the selector know which sockets should be ready to write/read first? Which information do i miss to understand this?

Server:

JavaScript

Client:

JavaScript

Advertisement

Answer

Sockets don’t actually write directly to the peer and they don’t read from the peer. Instead they write into a local socket specific write buffer and read from a socket specific read buffer. The OS kernel cares about the delivery of the data from the socket write buffer to the peer and puts received packets from the peer into the sockets receive buffer.

The status of these in-kernel socket buffers and changes to these buffers can be monitored with functions like select, poll, kqueue. In essence: a socket is considered writable if there is room in the sockets write buffer. A socket is considered readable if there are data in the sockets read buffer.

Advertisement