CodingBowl

Python Socket Programming in 10 Simple Steps (with Multi-Client Support)

Published on 14 Jun 2025Python
image
Photo by Solen Feyissa on Unsplash

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.

  1. Import Required Modules
    import socket
    import threading
    
  2. 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()
    
  3. Set Server Address and Port
    HOST = '127.0.0.1'
    PORT = 5555
    
  4. Create a Socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    
  5. Bind the Socket
        s.bind((HOST, PORT))
    
  6. Start Listening for Connections
        s.listen()
        print("Server listening...")
    
  7. Accept Clients in a Loop
        while True:
            conn, addr = s.accept()
    
  8. Start a New Thread for Each Client
            thread = threading.Thread(target=handle_client, args=(conn, addr))
            thread.start()
    
  9. 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()}")
    
  10. 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!

Meow! AI Assistance Note

This post was created with the assistance of Gemini AI and ChatGPT.
It is shared for informational purposes only and is not intended to mislead, cause harm, or misrepresent facts. While efforts have been made to ensure accuracy, readers are encouraged to verify information independently. Portions of the content may not be entirely original.

image
Photo by Yibo Wei on Unsplash