Advanced Python Tutorial: Networking and Sockets

Advanced Python Tutorial 8: Networking and Sockets

🌐 What are Sockets?

Sockets allow two machines (or programs) to communicate over a network using protocols like TCP or UDP. In Python, the built-in socket module makes it easy to build clients and servers.

🖥️ TCP Server Example

This server listens for incoming connections and responds with a greeting.


import socket

HOST = '127.0.0.1'  # localhost
PORT = 65432        # non-privileged port

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print("Server is listening...")
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        data = conn.recv(1024)
        if data:
            conn.sendall(b'Hello Client!')
    

📱 TCP Client Example

This client connects to the server and receives the message.


import socket

HOST = '127.0.0.1'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello Server!')
    data = s.recv(1024)
    print('Received from server:', data.decode())
    

💡 Real-World Use: Mini Chat App

This kind of client-server structure is the base of chat servers, multiplayer games, and remote device communication.

  • 🟢 A server accepts multiple clients (with threads or asyncio)
  • 📤 Clients send messages to server
  • 📨 Server relays messages or stores data

📌 Summary

  • Sockets are the foundation of networking in Python.
  • Use AF_INET and SOCK_STREAM for TCP communication.
  • Test with localhost before deploying to live networks.

Comments