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 multithreaded chat server

So let's put this to use and write our chat server. Make a new file called 2.1-chat_server-multithread.py and put the following code in it:

import threading, queue import tincanchat HOST = tincanchat.HOST PORT = tincanchat.PORT send_queues = {} lock = threading.Lock() def handle_client_recv(sock, addr): """ Receive messages from client and broadcast them to other clients until client disconnects """ rest = bytes() while True: try: (msgs, rest) = tincanchat.recv_msgs(sock, rest) except (EOFError, ConnectionError): handle_disconnect(sock, addr) break for msg in msgs: msg = '{}: {}'.format(addr, msg) print(msg) broadcast_msg(msg) def handle_client_send(sock, q, addr): """ Monitor queue for new messages, send them to client ...

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