1. 网络编程基础
网络编程就是让程序通过网络发送数据给其他程序或接收其他程序的数据。Python中的网络编程主要使用 socket 模块。
2. TCP服务器示例
import socket
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))
# 监听连接
server_socket.listen(5)
print('Server listening on port:', port)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
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()
这个简单的服务器监听12345端口,当有客户端连接时,会打印客户端地址,并接收客户端的消息,然后发送响应并关闭连接。
3. TCP客户端示例
import socket
# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
host = 'localhost'
port = 12345
client_socket.connect((host, port))
# 发送消息
msg = 'Hello, server!'
client_socket.send(msg.encode())
# 接收响应
response = client_socket.recv(1024).decode()
print('Response from server:', response)
# 关闭连接
client_socket.close()
这个简单的客户端连接服务器,发送一条消息,接收服务器的响应,并关闭连接。
4. UDP服务器示例
import socket
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))
print('Server listening on port:', port)
while True:
# 接收客户端消息
msg, addr = server_socket.recvfrom(1024)
print('Message from client:', msg.decode(), 'at', addr)
# 发送响应
response = 'Thank you for your message'
server_socket.sendto(response.encode(), addr)
这个简单的UDP服务器监听12345端口,接收客户端的消息,然后发送响应。
5. UDP客户端示例
import socket
# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送消息
host = 'localhost'
port = 12345
msg = 'Hello, server!'
client_socket.sendto(msg.encode(), (host, port))
# 接收响应
response, addr = client_socket.recvfrom(1024)
print('Response from server:', response.decode())
# 关闭连接
client_socket.close()
这个简单的UDP客户端发送一条消息,接收服务器的响应,并关闭连接。
6. 多线程TCP服务器示例
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()
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))
# 监听连接
server_socket.listen(5)
print('Server listening on port:', port)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
# 在新线程中处理客户端连接
thread = threading.Thread(target=handle_client, args=(client_socket, addr))
thread.start()
这个服务器使用多线程处理多个客户端连接,每个客户端连接都在一个新线程中处理。
7. 非阻塞I/O TCP服务器示例
import socket
import select
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置为非阻塞模式
server_socket.setblocking(False)
# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))
# 监听连接
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:
# 建立客户端连接
client_socket, addr = server_socket.accept()
client_socket.setblocking(False)
inputs.append(client_socket)
print('Got connection from', addr)
else:
# 接收客户端消息
data = sock.recv(1024)
if data:
print('Message from client:', data.decode())
sock.send(data.upper())
else:
# 客户端断开连接
print('Client disconnected')
inputs.remove(sock)
sock.close()
这个非阻塞TCP服务器使用select模块同时处理多个客户端连接,提高了程序的响应速度。
8. 使用HTTP协议示例
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())
# 创建 HTTP 服务器
server_address = ('localhost', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print('Starting simple HTTP server...')
httpd.serve_forever()
这个简单的HTTP服务器监听8000端口,当收到GET请求时,返回“Hello, World!”的响应。
9. 发送HTTP请求示例
首先安装requests库:
pip install requests
然后编写代码:
import requests
url = 'http://localhost:8000'
response = requests.get(url)
print('Response status code:', response.status_code)
print('Response content:', response.text)
这段代码向本地HTTP服务器发送GET请求,并打印响应的状态码和内容。
10. WebSocket编程示例
首先安装websockets库:
pip install websockets
然后编写代码:
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
print(f'Received message: {message}')
await websocket.send(message)
# 创建 WebSocket 服务器
start_server = websockets.serve(echo, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
这个简单的WebSocket服务器监听8765端口,当收到消息时,将其原样返回。
11. 使用WebSocket客户端示例
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())
这个简单的WebSocket客户端连接服务器,发送一条消息,并接收服务器的响应。
12. 实战案例:实时聊天应用
接下来,我们将创建一个简单的实时聊天应用,包括一个WebSocket服务器和多个客户端。
(1) 创建WebSocket服务器
import asyncio
import websockets
connected_clients = set()
async def broadcast(message):
if connected_clients:
await asyncio.wait([client.send(message) for client in connected_clients])
async def chat(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
print(f'Received message: {message}')
await broadcast(message)
finally:
connected_clients.remove(websocket)
# 创建 WebSocket 服务器
start_server = websockets.serve(chat, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
这个WebSocket服务器监听8765端口,并将所有客户端的消息广播给其他客户端。
(2) 创建WebSocket客户端
import asyncio
import websockets
async def chat_client():
uri = 'ws://localhost:8765'
async with websockets.connect(uri) as websocket:
while True:
message = input('Enter your message: ')
await websocket.send(message)
print('Sent message:', message)
response = await websocket.recv()
print('Received response:', response)
asyncio.get_event_loop().run_until_complete(chat_client())
这个WebSocket客户端连接服务器,发送消息,并接收服务器的广播消息。