A simple echo server

As we work through this chapter, we'll find ourselves reusing several pieces of code, so to save ourselves from repetition, we'll set up a module with useful functions that we can reuse as we go along. Create a file called tincanchat.py and save the following code in it:

import socket HOST = '' PORT = 4040 def create_listen_socket(host, port): """ Setup the sockets our server will receive connection requests on """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(100) return sock def recv_msg(sock): """ Wait for data to arrive on the socket, then parse into messages using b'\0' as message delimiter """ data = bytearray() msg ...

Get Learning Python Network Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.