SoFunction
Updated on 2025-04-17

Detailed explanation of examples of Python implementing common network communications

1. HTTP/HTTPS communication

1. Client example (requests library)

import requests

# HTTP GET
response = ('/get')
print()

# HTTPS POST
response = (
    '/post',
    data={'key': 'value'},
    verify=True  # Verify SSL certificate (default))
print(())

2. Server side example (Flask)

from flask import Flask, request

app = Flask(__name__)

@('/api', methods=['GET', 'POST'])
def handle_request():
    if  == 'GET':
        return {'message': 'GET received'}
    elif  == 'POST':
        return {'data': }

if __name__ == '__main__':
    (ssl_context='adhoc')  # Enable HTTPS

2. UDP communication

1. Server side

import socket

server = (socket.AF_INET, socket.SOCK_DGRAM)
(('0.0.0.0', 9999))

while True:
    data, addr = (1024)
    print(f"Received from {addr}: {()}")
    (b'UDP response', addr)

2. Client

import socket

client = (socket.AF_INET, socket.SOCK_DGRAM)
(b'Hello UDP', ('localhost', 9999))
response, addr = (1024)
print(f"Received: {()}")

3. WebSocket Communication

Requires installation of the library:pip install websockets

1. Server side

import asyncio
import websockets

async def handler(websocket):
    async for message in websocket:
        print(f"Received: {message}")
        await (f"Echo: {message}")

async def main():
    async with (handler, "localhost", 8765):
        await ()  # Permanently run
(main())

2. Client

import asyncio
import websockets

async def client():
    async with ("ws://localhost:8765") as ws:
        await ("Hello WebSocket!")
        response = await ()
        print(f"Received: {response}")

(client())

4. Server-Sent Events (SSE)

Requires installation of the library:pip install sseclient-py

1. Server side (Flask implementation)

from flask import Flask, Response

app = Flask(__name__)

@('/stream')
def stream():
    def event_stream():
        for i in range(5):
            yield f"data: Message {i}\n\n"
    return Response(event_stream(), mimetype="text/event-stream")

if __name__ == '__main__':
    ()

2. Client

import requests
from sseclient import SSEClient

url = 'http://localhost:5000/stream'
response = (url, stream=True)
client = SSEClient(response)

for event in ():
    print(f"Received event: {}")

Key points description

  • HTTP/HTTPS: The most commonly used request-response model
  • UDP: No connection protocol, suitable for scenarios with high real-time requirements
  • WebSocket: Full duplex communication protocol, suitable for real-time two-way communication
  • SSE: One-way push technology from server to client
  • Safety advice
    • HTTPS uses requestsverify=TrueVerification certificate
    • WebSocket usagewss://Security Agreement
    • The production environment should use a formal SSL certificate

Choose an agreement according to specific needs:

  • Simple data request: HTTP/HTTPS
  • Real-time game/video: UDP
  • Chat application: WebSocket
  • Real-time notification: SSE

It is recommended to use asynchronous frameworks (such as aiohttp, FastAPI) according to actual scenarios to obtain better performance.

This is the end of this article about the detailed explanation of Python's examples to implement common network communication. For more related Python network communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!