# Source: F. Sarker, S. Washington. "Learning Python Network Programming" import socket #HOST = '127.0.0.1' # Listen only to localhost HOST = '' # Listen to all interfaces 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 a message delimiter""" data = bytearray() msg = '' # Repeatedly read 4096 Bytes off the socket, storing the bytes # in data until we see a message delimiter while not msg: recvd = sock.recv(4096) if not recvd: # Socket has been closed prematurely raise ConnectionError() data = data + recvd if b'\0' in recvd: msg = data.rstrip(b'\0') msg = msg.decode('utf-8') return msg def prep_msg(msg): """ Prepare a string to be sent as a message """ msg += '\0' return msg.encode('utf-8') def send_msg(sock, msg): """ Send string over a socet, preparing it first """ data = prep_msg(msg) sock.sendall(data)