Python Socket Programming with Examples

Share Your Love

Python socket programming allows you to establish network connections, and send and receive data over the network using the sockets library. Sockets provide a low-level interface for network communication and can be used to implement various network protocols. Here’s a basic example of socket programming in Python:

Server Side:

import socket

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Define the server address and port
server_address = ('localhost', 8000)

# Bind the socket to the server address and port
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(1)

print('Server listening on {}:{}'.format(*server_address))

while True:
    # Accept a client connection
    client_socket, client_address = server_socket.accept()
    print('Received connection from {}:{}'.format(*client_address))

    # Receive data from the client
    data = client_socket.recv(1024)
    print('Received data:', data.decode())

    # Send a response back to the client
    response = 'Hello from the server!'
    client_socket.sendall(response.encode())

    # Close the client socket
    client_socket.close()

Client Side:

import socket

# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Define the server address and port
server_address = ('localhost', 8000)

# Connect to the server
client_socket.connect(server_address)

# Send data to the server
message = 'Hello from the client!'
client_socket.sendall(message.encode())

# Receive the server's response
response = client_socket.recv(1024)
print('Received response:', response.decode())

# Close the client socket
client_socket.close()

In the example above, we have simple client-server communication. The server creates a socket using socket.socket() and binds it to a specific address and port using bind(). It then listens for incoming connections using listen(). Once a client connects using accept(), it receives data from the client using recv(), sends a response using sendall(), and finally closes the client socket.

On the client side, a socket is created using socket.socket(). It connects to the server using connect(), sends data using sendall(), receives the server’s response using recv(), and then closes the socket.

Note that in this example, we used a TCP socket (socket.SOCK_STREAM) for reliable, connection-oriented communication. You can also use UDP sockets (socket.SOCK_DGRAM) for connectionless, unreliable communication.

Socket Programming On Different Scenarios

Examples of Python socket programming for different scenarios – 1:

  1. Broadcasting Server:
import socket

# Create a UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

# Bind the socket to a specific address and port
server_address = ('', 9000)
server_socket.bind(server_address)

print('Server listening on {}:{}'.format(*server_address))

while True:
    # Receive data from clients
    data, address = server_socket.recvfrom(1024)
    print('Received data from {}:{}'.format(*address))
    print('Data:', data.decode())

    # Send a response back to the client
    response = 'Hello from the server!'
    server_socket.sendto(response.encode(), address)

In this example, we create a UDP socket and enable broadcasting using the setsockopt() function. The server binds to a specific address and port, listens for incoming messages with recvfrom(), and sends a response back to the client using sendto().

  1. HTTP Client:
import socket

# Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
server_address = ('www.example.com', 80)
client_socket.connect(server_address)

# Send an HTTP request to the server
request = "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"
client_socket.sendall(request.encode())

# Receive the server's response
response = b''
while True:
    data = client_socket.recv(1024)
    if not data:
        break
    response += data

print('Received response:', response.decode())

# Close the client socket
client_socket.close()

In this example, we create a TCP socket and connect to an HTTP server. We send an HTTP GET request to the server and receive the server’s response in multiple chunks using a loop. The response is accumulated in the response variable and then printed.

  1. Multithreaded Server:
import socket
import threading

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Define the server address and port
server_address = ('localhost', 8000)

# Bind the socket to the server address and port
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(5)
print('Server listening on {}:{}'.format(*server_address))

def handle_client(client_socket):
    # Receive data from the client
    data = client_socket.recv(1024)
    print('Received data:', data.decode())

    # Send a response back to the client
    response = 'Hello from the server!'
    client_socket.sendall(response.encode())

    # Close the client socket
    client_socket.close()

while True:
    # Accept a client connection
    client_socket, client_address = server_socket.accept()
    print('Received connection from {}:{}'.format(*client_address))

    # Start a new thread to handle the client
    client_thread = threading.Thread(target=handle_client, args=(client_socket,))
    client_thread.start()

In this example, we create a multithreaded server that can handle multiple client connections simultaneously. Each client connection is handled in a separate thread. The handle_client() function is responsible for receiving data from the client, sending a response, and closing the client socket.

These examples demonstrate different use cases of socket programming in Python, including broadcasting, HTTP communication, and multithreading. They provide a starting point for building more complex network applications based on your specific requirements.

Real-time examples of Python socket programming Scenarios – 2:

  1. Chat Server:
import socket
import threading

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Define the server address and port
server_address = ('localhost', 8000)

# Bind the socket to the server address and port
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(5)
print('Server listening on {}:{}'.format(*server_address))

# List to store connected clients
clients = []

def handle_client(client_socket, client_address):
    while True:
        # Receive data from the client
        data = client_socket.recv(1024)
        if not data:
            break

        # Broadcast the message to all connected clients
        message = '[{}:{}]: {}'.format(*client_address, data.decode())
        for client in clients:
            if client != client_socket:
                client.sendall(message.encode())

    # Remove the client from the list
    clients.remove(client_socket)
    client_socket.close()

while True:
    # Accept a client connection
    client_socket, client_address = server_socket.accept()
    print('Received connection from {}:{}'.format(*client_address))

    # Add the client to the list
    clients.append(client_socket)

    # Start a new thread to handle the client
    client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
    client_thread.start()

In this example, we create a chat server that allows multiple clients to connect and exchange messages in real-time. Each connected client is stored in the clients list. The handle_client() function runs in a separate thread for each client and handles the sending and receiving of messages. When a client sends a message, the server broadcasts it to all other connected clients.

  1. Real-Time Data Streaming:
import socket
import time

# Create a UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Bind the socket to a specific address and port
server_address = ('localhost', 9000)
server_socket.bind(server_address)

print('Server listening on {}:{}'.format(*server_address))

while True:
    # Generate some data
    data = str(time.time())

    # Send the data to clients
    server_socket.sendto(data.encode(), ('localhost', 9001))

    # Sleep for a while before sending the next data
    time.sleep(1)

In this example, we create a real-time data streaming server using UDP sockets. The server continuously generates data (in this case, the current timestamp) and sends it to a specific address and port using sendto(). Clients can connect to the server at the specified address and port to receive the data in real-time.

You can adapt and expand them based on your specific use cases, such as building multiplayer games, real-time monitoring systems, or any application that requires real-time communication and data streaming.

Real-time examples of Python socket programming Scenarios – 3:

  1. Real-Time Stock Market Data:
import socket
import requests

# Create a UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Bind the socket to a specific address and port
server_address = ('localhost', 9000)
server_socket.bind(server_address)

print('Server listening on {}:{}'.format(*server_address))

while True:
    # Fetch stock market data from an API
    response = requests.get('https://api.example.com/stocks')
    data = response.json()

    # Send the data to clients
    server_socket.sendto(str(data).encode(), ('localhost', 9001))

    # Sleep for a while before fetching the next data
    time.sleep(5)

In this example, we create a server that fetches real-time stock market data from an API at regular intervals and sends it to connected clients using UDP sockets. The data is obtained by making an HTTP request to the API, and the fetched data is sent to clients for real-time monitoring or analysis.

  1. Real-Time Sensor Data Monitoring:
import socket
import random

# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific address and port
server_address = ('localhost', 8000)
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(5)
print('Server listening on {}:{}'.format(*server_address))

while True:
    # Accept a client connection
    client_socket, client_address = server_socket.accept()
    print('Received connection from {}:{}'.format(*client_address))

    while True:
        # Generate random sensor data
        sensor_data = random.randint(0, 100)

        # Send the sensor data to the client
        client_socket.sendall(str(sensor_data).encode())

        # Sleep for a while before sending the next data
        time.sleep(1)

    # Close the client socket
    client_socket.close()

In this example, we create a server that continuously generates random sensor data and sends it to a connected client using TCP sockets. The server simulates real-time sensor data monitoring, where the generated sensor data is sent to the client for real-time analysis or visualization.

These examples demonstrate how Python socket programming can be used in various real-time scenarios, such as real-time data feeds, monitoring systems, or any application that requires continuous data streaming and communication. Developers can customize and enhance these examples based on your specific requirements and integrate them into larger systems or applications.

Here’s another real-time example of Python socket programming Scenarios – 4:

Real-Time Chat Application with Multiple Clients:

import socket
import threading

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Define the server address and port
server_address = ('localhost', 8000)

# Bind the socket to the server address and port
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(5)
print('Server listening on {}:{}'.format(*server_address))

# List to store connected clients
clients = []
lock = threading.Lock()

def broadcast(message, sender_socket):
    # Send the message to all connected clients except the sender
    for client in clients:
        if client != sender_socket:
            client.sendall(message)

def handle_client(client_socket):
    while True:
        # Receive data from the client
        data = client_socket.recv(1024)
        if not data:
            break

        # Broadcast the message to all connected clients
        message = '[Client]: {}'.format(data.decode())
        with lock:
            broadcast(message.encode(), client_socket)

    # Remove the client from the list
    with lock:
        clients.remove(client_socket)
    client_socket.close()

while True:
    # Accept a client connection
    client_socket, client_address = server_socket.accept()
    print('Received connection from {}:{}'.format(*client_address))

    # Add the client to the list
    with lock:
        clients.append(client_socket)

    # Start a new thread to handle the client
    client_thread = threading.Thread(target=handle_client, args=(client_socket,))
    client_thread.start()

In this example, we create a real-time chat application where multiple clients can connect to the server and exchange messages in real-time. Each connected client is stored in the clients list, and a separate thread is spawned to handle each client. The handle_client() function runs in a thread and receives messages from the client, then broadcasts the message to all other connected clients using the broadcast() function.

Clients can connect to the server using TCP sockets and send messages to the server. The server then broadcasts those messages to all other connected clients, allowing for real-time chat communication between multiple clients.

This example demonstrates a simple implementation of a real-time chat application using Python socket programming. You can further enhance this application by adding features like username registration, private messaging, or handling client disconnections.

Here’s another example that builds upon the previous real-time sensor data streaming to a web browser Scenarios – 5.

In this enhanced version, we’ll introduce dynamic client updates using WebSockets for a more interactive and efficient real-time experience.

To use WebSockets, we’ll leverage the websockets library, which provides a simple interface for creating WebSocket servers and clients.

First, let’s install the websockets library using pip install websockets.

Enhanced Real-Time Sensor Data Streaming with WebSockets:

import socket
import asyncio
import websockets

# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific address and port
server_address = ('localhost', 8000)
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(1)
print('Server listening on {}:{}'.format(*server_address))

# Store the latest sensor data
latest_data = ''

async def handle_client(websocket, path):
    global latest_data

    # Send the latest data to the client on connection
    await websocket.send(latest_data)

    while True:
        # Receive data from the client
        data = await websocket.recv()
        if not data:
            break

        # Store the received data as the latest sensor data
        latest_data = data

        # Broadcast the latest data to all connected clients
        await asyncio.wait([client.send(data) for client in connected_clients])

# Store a set of connected clients
connected_clients = set()

async def start_server():
    # Start the WebSocket server
    async with websockets.serve(handle_client, 'localhost', 8765):
        await asyncio.Future()  # Keep the server running

# Start the WebSocket server in a separate event loop
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server())

while True:
    # Accept a client connection
    client_socket, client_address = server_socket.accept()
    print('Received connection from {}:{}'.format(*client_address))

    # Add the client to the set of connected clients
    connected_clients.add(client_socket)

    # Start a new thread to handle receiving data from the client
    client_thread = threading.Thread(target=receive_data, args=(client_socket,))
    client_thread.start()

In this enhanced example, we introduce WebSocket communication using the websockets library. We create a WebSocket server that listens on port 8765 and handles incoming connections and messages from clients.

Upon connection, the server sends the latest sensor data to the client. Any new data received from clients is considered the latest data, which is then stored and broadcast to all connected clients.

The server uses asyncio to handle asynchronous operations, and the WebSocket server runs in its own event loop. The HTTP server for serving the HTML content and the WebSocket server run in parallel.

With WebSockets, the client-side code can use JavaScript and the WebSocket API to establish a connection to the server and receive real-time updates as new sensor data is received.

This enhanced example provides a more interactive and efficient real-time data streaming experience compared to the previous HTTP refresh-based approach.

Note: To run this example, you’ll need to install the websockets library using pip install websockets.

Conclusion:

These examples showcase the versatility of Python socket programming in real-time applications. Socket programming in Python provides a flexible and powerful way to communicate over a network. Developers can extend this basic example to implement more complex network applications and protocols.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter