Network programming allows programs to send or receive data through the network. In Python, network programming primarily uses the
socket
module.
1. Basics of Network Programming
Network programming enables programs to send data to other programs through a network or receive data from other programs. In Python, the socket
module is mainly used for this purpose.
2. TCP Server Example
import socket # Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the port host = 'localhost' port = 12345 server_socket.bind((host, port)) # Listen for connections server_socket.listen(5) print('Server listening on port:', port) while True: # Establish client connection client_socket, addr = server_socket.accept() print('Got connection from', addr) # Receive message from client msg = client_socket.recv(1024).decode() print('Message from client:', msg) # Send response response = 'Thank you for connecting' client_socket.send(response.encode()) # Close connection client_socket.close()
This simple TCP server listens on port 12345. When a client connects, it prints the client's address, receives a message, sends a response, and then closes the connection.
3. TCP Client Example
import socket # Create a socket object client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to server host = 'localhost' port = 12345 client_socket.connect((host, port)) # Send message msg = 'Hello, server!' client_socket.send(msg.encode()) # Receive response response = client_socket.recv(1024).decode() print('Response from server:', response) # Close connection client_socket.close()
This simple TCP client connects to the server, sends a message, receives the server’s response, and then closes the connection.
4. UDP Server Example
import socket # Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the port host = 'localhost' port = 12345 server_socket.bind((host, port)) print('Server listening on port:', port) while True: # Receive message from client msg, addr = server_socket.recvfrom(1024) print('Message from client:', msg.decode(), 'at', addr) # Send response response = 'Thank you for your message' server_socket.sendto(response.encode(), addr)
This simple UDP server listens on port 12345, receives messages from clients, and sends a response.
5. UDP Client Example
import socket # Create a socket object client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Send message host = 'localhost' port = 12345 msg = 'Hello, server!' client_socket.sendto(msg.encode(), (host, port)) # Receive response response, addr = client_socket.recvfrom(1024) print('Response from server:', response.decode()) # Close connection client_socket.close()
This simple UDP client sends a message to the server, receives a response, and closes the connection.
6. Multi-threaded TCP Server Example
import socket import threading def handle_client(client_socket, addr): print('Got connection from', addr) msg = client_socket.recv(1024).decode() print('Message from client:', msg) response = 'Thank you for connecting' client_socket.send(response.encode()) client_socket.close() # Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the port host = 'localhost' port = 12345 server_socket.bind((host, port)) # Listen for connections server_socket.listen(5) print('Server listening on port:', port) while True: # Establish client connection client_socket, addr = server_socket.accept() # Handle client connection in a new thread thread = threading.Thread(target=handle_client, args=(client_socket, addr)) thread.start()
This server uses multi-threading to handle multiple client connections, with each client handled in a separate thread.
7. Non-blocking I/O TCP Server Example
import socket import select # Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Set the socket to non-blocking mode server_socket.setblocking(False) # Bind the port host = 'localhost' port = 12345 server_socket.bind((host, port)) # Listen for connections server_socket.listen(5) print('Server listening on port:', port) inputs = [server_socket] outputs = [] while True: readable, writable, exceptional = select.select(inputs, outputs, inputs) for sock in readable: if sock == server_socket: # Establish client connection client_socket, addr = server_socket.accept() client_socket.setblocking(False) inputs.append(client_socket) print('Got connection from', addr) else: # Receive message from client data = sock.recv(1024) if data: print('Message from client:', data.decode()) sock.send(data.upper()) else: # Client disconnected print('Client disconnected') inputs.remove(sock) sock.close()
This non-blocking TCP server uses the select
module to handle multiple client connections simultaneously, improving the program's responsiveness.
8. HTTP Protocol Example
from http.server import HTTPServer, BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() message = 'Hello, World!' self.wfile.write(message.encode()) # Create HTTP server server_address = ('localhost', 8000) httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) print('Starting simple HTTP server...') httpd.serve_forever()
This simple HTTP server listens on port 8000 and responds with “Hello, World!” when it receives a GET request.
9. Sending HTTP Request Example
First, install the requests
library:
pip install requests
Then, write the following code:
import requests url = 'http://localhost:8000' response = requests.get(url) print('Response status code:', response.status_code) print('Response content:', response.text)
This code sends a GET request to the local HTTP server and prints the status code and content of the response.
10. WebSocket Programming Example
First, install the websockets
library:
pip install websockets
Then, write the following code:
import asyncio import websockets async def echo(websocket, path): async for message in websocket: print(f'Received message: {message}') await websocket.send(message) # Create WebSocket server start_server = websockets.serve(echo, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
This simple WebSocket server listens on port 8765 and echoes any message it receives.
11. WebSocket Client Example
import asyncio import websockets async def send_message(): uri = 'ws://localhost:8765' async with websockets.connect(uri) as websocket: message = 'Hello, WebSocket!' await websocket.send(message) print(f'Sent message: {message}') response = await websocket.recv() print(f'Received response: {response}') asyncio.get_event_loop().run_until_complete(send_message())
This simple WebSocket client connects to the server, sends a message, and receives a response from the server.