CodingBowl

Python Socket Programming in 10 Simple Steps

Published on 13 Jun 2025Python
image
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
  2. 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...")
  3. Accept a client connection
    client_socket, address = server.accept()
    print(f"Connected to {address}")
  4. Receive a message from the client
    data = client_socket.recv(1024).decode()
    print(f"Client says: {data}")
  5. Send a response to the client
    client_socket.send("Hello from server!".encode())
    client_socket.close()
  6. Create client.py
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('localhost', 5555))
  7. Send a message to the server
    client.send("Hi Server!".encode())
  8. Receive a response from the server
    response = client.recv(1024).decode()
    print(f"Server says: {response}")
    client.close()
  9. Run the server
    python3 server.py
  10. 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.

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