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
-
Import the socket module
import socket
-
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...")
-
Accept a client connection
client_socket, address = server.accept() print(f"Connected to {address}")
-
Receive a message from the client
data = client_socket.recv(1024).decode() print(f"Client says: {data}")
-
Send a response to the client
client_socket.send("Hello from server!".encode()) client_socket.close()
-
Create client.py
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 5555))
-
Send a message to the server
client.send("Hi Server!".encode())
-
Receive a response from the server
response = client.recv(1024).decode() print(f"Server says: {response}") client.close()
-
Run the server
python3 server.py
-
Run the client
python3 client.py
How to Run This in GitHub Codespace
- Open your Codespace in GitHub (any repo is fine).
- Create
server.py
andclient.py
and paste in the code. - Open two terminal tabs.
- Run the server first:
python3 server.py
- 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.