python 实现客户端和服务端接发数据
时间: 2024-09-23 18:05:28 浏览: 60
在Python中,我们可以使用socket模块来实现客户端和服务端的数据通信。以下是基本的步骤:
**服务端(Server):**
```python
import socket
def start_server():
# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('localhost', 12345)
server_socket.bind(server_address)
# 开始监听连接
server_socket.listen(1) # 监听队列长度为1
print(f"服务器正在监听...{server_address}")
while True:
# 等待连接
connection, client_address = server_socket.accept()
print(f"连接来自: {client_address}")
# 接收客户端消息
data = connection.recv(1024)
print("Received:", data.decode())
# 发送响应
response = "Hello from Server!"
connection.sendall(response.encode())
# 关闭连接
connection.close()
start_server()
```
**客户端(Client):**
```python
import socket
def send_data_to_server(message):
# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
server_address = ('localhost', 12345)
client_socket.connect(server_address)
print(f"已连接到: {server_address}")
# 发送数据
client_socket.sendall(message.encode())
print("Sent:", message)
# 接收服务器响应
received_message = client_socket.recv(1024).decode()
print("Received:", received_message)
# 关闭连接
client_socket.close()
# 示例:向服务器发送消息
send_data_to_server("Hello, Server!")
```
阅读全文