O'Reilly logo

Learning Python Network Programming by Sam Washington, Dr. M. O. Faruque Sarker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required