1. 创建服务器
import socket
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定主机和端口
server_address = ('localhost', 12345)
server_socket.bind(server_address)
# 设置最大连接数
server_socket.listen(5)
print("Server is listening on", server_address)
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print("Connection from", client_address)
# 接收数据
data = client_socket.recv(1024)
print("Received:", data.decode('utf-8'))
# 发送响应
response = "Hello, client!"
client_socket.send(response.encode('utf-8'))
# 关闭连接
client_socket.close()
2. 创建客户端
import socket
# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
server_address = ('localhost', 12345)
client_socket.connect(server_address)
# 发送数据
message = "Hello, server!"
client_socket.send(message.encode('utf-8'))
# 接收响应
response = client_socket.recv(1024)
print("Server response:", response.decode('utf-8'))
# 关闭连接
client_socket.close()
3. UDP 服务器和客户端
UDP(用户数据报协议)是一种无连接的协议,以下是一个简单的 UDP 服务器和客户端示例:
UDP 服务器
import socket
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定主机和端口
server_address = ('localhost', 12345)
server_socket.bind(server_address)
print("UDP Server is listening on", server_address)
while True:
# 接收数据
data, client_address = server_socket.recvfrom(1024)
print("Received:", data.decode('utf-8'), "from", client_address)
# 发送响应
response = "Hello, client!"
server_socket.sendto(response.encode('utf-8'), client_address)
UDP 客户端
import socket
# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
message = "Hello, server!"
client_socket.sendto(message.encode('utf-8'), ('localhost', 12345))
# 接收响应
response, server_address = client_socket.recvfrom(1024)
print("Server response:", response.decode('utf-8'), "from", server_address)
# 关闭连接
client_socket.close()
这些示例演示了基本的 TCP 和 UDP 服务器/客户端通信。在实际应用中,你可能还需要考虑异常处理、多线程/多进程编程、协议设计等方面的问题。此外,对于更复杂的网络应用程序,你可能会考虑使用框架(如 Flask、Django)来简化开发。
转载请注明出处:http://www.pingtaimeng.com/article/detail/234/Python3