实现服务器和客户端双向通信 客户端和服务器都可以收发
时间: 2024-02-01 15:02:15 浏览: 93
要实现服务器和客户端之间的双向通信,你可以使用网络编程中的套接字(Socket)来实现。下面是一个简单的示例代码,演示了如何使用Python的socket模块实现客户端和服务器之间的双向通信:
服务器端代码(server.py):
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名和端口号
host = socket.gethostname()
port = 12345
# 绑定主机名和端口号
server_socket.bind((host, port))
# 设置最大连接数
server_socket.listen(5)
while True:
# 建立客户端连接
client_socket, addr = server_socket.accept()
print('连接地址:', addr)
# 从客户端接收数据
data = client_socket.recv(1024).decode()
print('客户端消息:', data)
# 向客户端发送数据
response = '服务器已收到消息:' + data
client_socket.send(response.encode())
# 关闭连接
client_socket.close()
```
客户端代码(client.py):
```python
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名和端口号
host = socket.gethostname()
port = 12345
# 连接服务器
client_socket.connect((host, port))
# 向服务器发送数据
message = 'Hello, server!'
client_socket.send(message.encode())
# 接收服务器响应
response = client_socket.recv(1024).decode()
print('服务器响应:', response)
# 关闭连接
client_socket.close()
```
在运行这两个代码文件之前,请确保你的网络环境可以进行网络通信,并且服务器端代码先于客户端代码运行。执行以上代码后,你将看到服务器端输出客户端发送的消息,并回复客户端已收到消息的确认信息。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)