Skip to content
Python

Python Socket Programming in 10 Simple Steps

Socket programming allows communication between computers or programs over a network. With Python’s built-in socket module, you can build your own basic client-server system — the foundation of many applications like chat apps, games, and IoT systems.

CodingBowl··1 min read
Photo by Steve Johnson on Unsplash

Create Your Own Server and Client

Introduction

Socket programming allows communication between computers or programs over a network. With Python’s built-in socket module, you can build your own basic client-server system — the foundation of many applications like chat apps, games, and IoT systems.

Step-by-Step Guide

  1. Import the socket module
`import socket`
  1. Create server.py
`server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 5555))
server.listen()
print("Server is listening on port 5555...")`
  1. Accept a client connection
`client_socket, address = server.accept()
print(f"Connected to {address}")`
  1. Receive a message from the client
`data = client_socket.recv(1024).decode()
print(f"Client says: {data}")`
  1. Send a response to the client
`client_socket.send("Hello from server!".encode())
client_socket.close()`
  1. Create client.py
`client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 5555))`
  1. Send a message to the server
`client.send("Hi Server!".encode())`
  1. Receive a response from the server
`response = client.recv(1024).decode()
print(f"Server says: {response}")
client.close()`
  1. Run the server
`python3 server.py`
  1. Run the client
`python3 client.py`

How to Run This in GitHub Codespace

  1. Open your Codespace in GitHub (any repo is fine).

  2. Create server.py and client.py and paste in the code.

  3. Open two terminal tabs.

  4. Run the server first: python3 server.py

  5. Run the client next: python3 client.py

The server will print what the client said, and the client will receive a response back — all within your Codespace.

Conclusion

You’ve created a working Python socket-based client-server communication system in just 10 steps. From here, you can expand it into chat apps, remote GPIO control for Raspberry Pi, or multiplayer game backends.