#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Very simple multithreading. Multiple TCP clients to connect to one server. @author: taylor@mst.edu """ import socket import threading def handler(client_socket: socket.socket, address: tuple[str, int]) -> None: """ Handles the part of the client work-flow that is client-dependent, and thus may be delayed (blocking program flow). """ while True: msg = client_socket.recv(1024) if not msg: break print(address, " sent message: ", msg) client_socket.send(msg) if msg.decode() == "quit": break print("server closing client socket, finishing one thread") client_socket.close() def main() -> None: s = socket.socket() port = 50002 print("Server started!") print("Waiting for clients...") s.bind(("", port)) s.listen(5) threads = [] try: while True: # This is the part that is not dependent on the client, # and therefore happens quickly (not blocking program flow). c, addr = s.accept() print("Got connection from", addr) new_thread = threading.Thread(target=handler, args=(c, addr)) new_thread.start() threads.append(new_thread) print(threads) except KeyboardInterrupt as err: print("you pressed ctrl-c", err) s.close() if __name__ == "__main__": main()