Home > Coding > python > Socket Programming in Python: Build a Client-Server Chat

Socket Programming in Python: Build a Client-Server Chat

What’s Socket Programming?

Sockets are endpoints for communication—your app’s way of saying, “Hey, let’s talk!” Python’s socket library makes it easy. We’ll:

  • Spin up a server VM listening on port 443.
  • Connect a client VM to it.
  • Chat back and forth once the session’s live.
  • Sneak in a file transfer—because why not?

This ties into QoS (data flow control) and DDoS (port misuse risks)—real-world stuff!


Setup: Two VMs

  • Server VM: IP 192.168.1.100 (example—use your own).
  • Client VM: Any IP on the same network (e.g., 192.168.1.101).
  • Tools: Python 3 installed on both (e.g., sudo apt install python3 on Ubuntu VMs via Linode).

Port 443 is HTTPS’s default—great for testing since it’s often open, but we’ll keep it simple (no SSL here—add it with ssl module if you’re fancy).


Server Code: Listen and Chat

Save this as server.py on your server VM:

python

import socket

# Create server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', 443))  # Listen on all interfaces, port 443
server_socket.listen(1)  # Accept 1 connection

print("Server listening on port 443...")

# Accept client connection
client_socket, addr = server_socket.accept()
print(f"Connected to {addr}")

# Chat loop
while True:
    # Receive client message
    client_msg = client_socket.recv(1024).decode()
    if not client_msg or client_msg.lower() == "exit":
        print("Client disconnected.")
        break
    print(f"Client: {client_msg}")

    # Send server message
    server_msg = input("Server: ")
    client_socket.send(server_msg.encode())

    # Bonus: Send a file if requested
    if client_msg.lower() == "send file":
        with open("server_file.txt", "rb") as f:
            client_socket.send(f.read())
        print("Sent server_file.txt to client!")

# Clean up
client_socket.close()
server_socket.close()

Run it:

bash

python3 server.py
  • Binds to 0.0.0.0:443—listens on all interfaces.
  • Waits for a client, then chats—type “exit” to quit.
  • If client says “send file,” it sends server_file.txt (create this file first—e.g., echo “Lazy Guy rocks!” > server_file.txt).

Client Code: Connect and Chat

Save this as client.py on your client VM:

python

import socket

# Create client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = "192.168.1.100"  # Replace with your server VM's IP
client_socket.connect((server_ip, 443))

print(f"Connected to {server_ip}:443")

# Chat loop
while True:
    # Send client message
    client_msg = input("Client: ")
    client_socket.send(client_msg.encode())
    if client_msg.lower() == "exit":
        print("Disconnecting...")
        break

    # Receive server message
    server_msg = client_socket.recv(1024).decode()
    if not server_msg:
        print("Server disconnected.")
        break
    print(f"Server: {server_msg}")

    # Bonus: Receive file if requested
    if client_msg.lower() == "send file":
        file_data = client_socket.recv(4096)  # Bigger buffer for file
        with open("received_file.txt", "wb") as f:
            f.write(file_data)
        print("Received file as received_file.txt!")

# Clean up
client_socket.close()

Run it:

bash

python3 client.py
  • Connects to 192.168.1.100:443—replace with your server IP.
  • Chats with the server—type “exit” to quit.
  • Type “send file” to get server_file.txt from the server.

How It Works

  1. Start Server: Run server.py on the server VM—listens on port 443.
  2. Connect Client: Run client.py on the client VM—connects to the server.
  3. Chat:
    • Client: “Hey, server!” → Server sees it, replies “Yo, client!”
    • Server: “What’s up?” → Client sees it, replies “Chillin’!”
  4. File Transfer:
    • Client: “send file” → Server sends server_file.txt.
    • Client saves it as received_file.txt—check it with cat received_file.txt.

Sample Output:

  • Server:Server listening on port 443... Connected to ('192.168.1.101', 12345) Client: Hey, server! Server: Yo, client!
  • Client:Connected to 192.168.1.100:443 Client: Hey, server! Server: Yo, client! Client: send file Received file as received_file.txt!

Bonus Feature: File Transfer

  • Why: Shows sockets aren’t just for chat—move files too! Think backups, logs, or even sneaky data in a DDoS test (don’t do that, though!).
  • How: Client requests “send file”—server sends server_file.txt—client saves it. Buffer’s 4096 bytes—handles small files (expand for bigger ones).
  • Use Case: Monitor server logs remotely—lazy admin vibes!

Useful Tips

  • Firewall: Open port 443 on the server VM—e.g., sudo ufw allow 443 (Ubuntu).
  • Real IPs: Replace 192.168.1.100 with your server’s actual IP (e.g., Linode public IP).
  • Security: Add SSL for real-world use—check Python’s ssl module (future post!).
  • Scale It: Add multi-client support with threading—lazy way to handle more connections.

Why It’s Cool for Lazy Guy

  • Networking 101: Sockets are DDoS playgrounds—flood port 443, and QoS saves the day!
  • Practical: Chat or share files—no bloated tools needed.
  • Passive Income: Teach this, slap ads on your blog—techies eat it up!

Try it on your VMs—drop a comment if you tweak it further. Stay lazy, stay connected!

Leave a Comment