Python用socket实现服务器和客户端的通信
时间: 2024-10-07 14:08:05 浏览: 39
在Python中,Socket库(socket模块)常用于实现网络通信,包括服务器端和客户端的连接。以下是简单概述:
**服务器端示例**:
```python
import socket
# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('localhost', 12345)
server_socket.bind(server_address)
# 开始监听连接
server_socket.listen(1) # 监听队列长度为1的连接请求
while True:
# 等待客户端连接
client_connection, client_address = server_socket.accept()
print(f"Accepted connection from {client_address}")
# 接收并处理客户端数据
data = client_connection.recv(1024).decode('utf-8')
print(f"Received message: {data}")
# 发送响应给客户端
response = "Hello from Server!"
client_connection.sendall(response.encode('utf-8'))
# 关闭连接
client_connection.close()
```
**客户端示例**:
```python
import socket
# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
client_address = ('localhost', 12345)
client_socket.connect(client_address)
# 发送消息到服务器
message = "Hello from Client!"
client_socket.sendall(message.encode('utf-8'))
# 接收服务器响应
response = client_socket.recv(1024).decode('utf-8')
print(f"Response received: {response}")
# 关闭连接
client_socket.close()
```
在上面的例子中,服务器等待客户端连接,然后接收、处理信息并发送回应。客户端则主动连接到服务器,发送消息并接收回复。
阅读全文