This guide walks you through building a simple Python socket server that can handle multiple clients at once, along with a basic client script. Follow these 10 steps to understand the essentials of network programming in Python.
-
Import Required Modules
import socket import threading
-
Define a Function to Handle Each Client
def handle_client(conn, addr): print(f"Connected by {addr}") data = conn.recv(1024) if data: print(f"Received from {addr}: {data.decode()}") conn.sendall(b"Hello from server!") conn.close()
-
Set Server Address and Port
HOST = '127.0.0.1' PORT = 5555
-
Create a Socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-
Bind the Socket
s.bind((HOST, PORT))
-
Start Listening for Connections
s.listen() print("Server listening...")
-
Accept Clients in a Loop
while True: conn, addr = s.accept()
-
Start a New Thread for Each Client
thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start()
-
Write the Client Code
import socket HOST = '127.0.0.1' PORT = 5555 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(b"Hello from client!") data = s.recv(1024) print(f"Received from server: {data.decode()}")
-
Run and Test
- Start the server: python server.py
- Run client.py in one or more terminals.
- Each client will connect, send a message, and receive a response.
- The server will handle all clients simultaneously!