python 循环收发 tcp 服务端与客户端脚本
时间: 2023-10-02 19:11:03 浏览: 106
python实现tcp服务器和客户端
以下是一个简单的 Python TCP 服务端与客户端脚本,可以循环收发消息:
TCP 服务端脚本:
```python
import socket
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8080
def handle_client(client_socket):
while True:
# 接收客户端消息
request = client_socket.recv(1024)
if not request:
break
print(f'Received message: {request.decode()}')
# 发送响应消息
response = f'You sent me: {request.decode()}'.encode()
client_socket.send(response)
# 关闭客户端连接
client_socket.close()
# 创建 TCP 套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定服务器地址和端口
server_socket.bind((SERVER_HOST, SERVER_PORT))
# 监听来自客户端的连接
server_socket.listen(1)
print(f'Server listening on {SERVER_HOST}:{SERVER_PORT}')
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print(f'Client connected from {client_address[0]}:{client_address[1]}')
# 处理客户端请求
handle_client(client_socket)
```
TCP 客户端脚本:
```python
import socket
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 8080
# 创建 TCP 套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f'Connected to {SERVER_HOST}:{SERVER_PORT}')
while True:
# 发送消息
message = input('> ')
client_socket.send(message.encode())
# 接收响应消息
response = client_socket.recv(1024)
print(f'Received response: {response.decode()}')
```
使用时,先运行服务端脚本,再运行客户端脚本,即可在客户端输入消息并发送,服务端将会收到并打印消息,并返回响应消息给客户端。客户端将会收到响应消息并打印。
阅读全文