import socket HOST = '' # Listen on all available interfaces PORT = 8080 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen(1) # Start listening for incoming connections print(f'Listening on {HOST}:{PORT}') conn, addr = s.accept() # Wait until a client connects and get client address with conn: print(f'Connected by {addr}') data = conn.recv(1024) # Receive data from client conn.sendall(data) # Send the received data back to client
import socket import threading HOST = '' PORT = 8080 def handle_client(conn, addr): with conn: print(f'Connected by {addr}') data = conn.recv(1024) conn.sendall(data) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen(5) print(f'Listening on {HOST}:{PORT}') while True: conn, addr = s.accept() t = threading.Thread(target=handle_client, args=(conn, addr)) t.start()This example creates a multithreaded server that can handle multiple clients simultaneously. It creates a new thread for each client that connects. In conclusion, the socket package is the library used for these examples, as it provides the `socket.socket()` and `socket.listen()` methods used.