Learning Python Network Programming

(Sean Pound) #1
Chapter 8

Our echo server should listen until a client connects and sends a bytes string, then
we want it to echo that string back to the client. We only need a few basic rules for
doing this. These rules are as follows:



  1. Communication will take place over TCP.

  2. The client will initiate an echo session by creating a socket connection to
    the server.

  3. The server will accept the connection and listen for the client to send a
    bytes string.

  4. The client will send a bytes string to the server.

  5. Once it sends the bytes string, the client will listen for a reply from the server

  6. When it receives the bytes string from the client, the server will send the
    bytes string back to the client.

  7. When the client has received the bytes string from the server, it will close its
    socket to end the session.


These steps are straightforward enough. The missing element here is how the server
and the client will know when a complete message has been sent. Remember that
an application sees a TCP connection as an endless stream of bytes, so we need to
decide what in that byte stream will signal the end of a message.


Framing


This problem is called framing, and there are several approaches that we can take to
handle it. The main ones are described here:



  1. Make it a protocol rule that only one message will be sent per connection,
    and once a message has been sent, the sender will immediately close
    the socket.

  2. Use fixed length messages. The receiver will read the number of bytes and
    know that they have the whole message.

  3. Prefix the message with the length of the message. The receiver will read the
    length of the message from the stream first, then it will read the indicated
    number of bytes to get the rest of the message.

  4. Use special character delimiters for indicating the end of a message. The
    receiver will scan the incoming stream for a delimiter, and the message
    comprises everything up to the delimiter.

Free download pdf