用python 详细编写网络通信器的设计代码
时间: 2024-12-20 18:25:28 浏览: 0
在网络编程中,Python 提供了多种库来处理网络通信,如socket模块用于创建套接字,以及内置的asyncio库支持异步IO,适用于高性能的服务器设计。这里是一个简单的TCP客户端和服务器的例子,使用`socket`模块:
```python
import socket
# 客户端示例
def client(host, port):
# 创建一个socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# 连接到指定主机和端口
client_socket.connect((host, port))
# 发送数据
message = "Hello, Server!"
client_socket.sendall(message.encode())
# 接收响应
response = client_socket.recv(1024)
print(f"Received: {response.decode()}")
except ConnectionRefusedError:
print("Connection refused")
finally:
# 关闭连接
client_socket.close()
# 服务器示例
def server(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
while True:
client, addr = server_socket.accept()
request = client.recv(1024)
print(f"Received from {addr}: {request.decode()}")
# 回应客户端
client.sendall("Hello, Client!".encode())
client.close()
if __name__ == "__main__":
host = "localhost"
port = 8000 # 可以修改为你想要监听的端口
client(host, port) # 要运行客户端,先运行一次服务端
server(host, port)
阅读全文