Skip to content
Python

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

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.

CodingBowl··1 min read
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
`
  1. 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()
`
  1. Set Server Address and Port
`HOST = '127.0.0.1'
PORT = 5555
`
  1. Create a Socket
`with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
`
  1. Bind the Socket
`    s.bind((HOST, PORT))
`
  1. Start Listening for Connections
`    s.listen()
print("Server listening...")
`
  1. Accept Clients in a Loop
`    while True:
conn, addr = s.accept()
`
  1. Start a New Thread for Each Client
`        thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
`
  1. 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()}")
`
  1. 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!