June 2015
Intermediate to advanced
320 pages
7h 18m
English
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 ...Read now
Unlock full access