python 循环收发 tcp 服务端与客户端脚本
时间: 2023-10-02 16:11:03 浏览: 95
以下是一个简单的 Python TCP 服务端与客户端脚本。服务端等待客户端连接并接收客户端发送的消息,然后将消息打印出来。客户端连接到服务端并发送一条消息。
### 服务端
```python
import socket
# 创建 TCP/IP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定套接字到端口
server_address = ('localhost', 10000)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)
# 开始监听传入的连接
sock.listen(1)
while True:
# 等待连接
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# 循环接收数据
while True:
data = connection.recv(1024)
print('received "%s"' % data.decode())
if data:
connection.sendall(data)
else:
break
finally:
# 清理连接
connection.close()
```
### 客户端
```python
import socket
# 创建 TCP/IP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接套接字到端口
server_address = ('localhost', 10000)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# 发送消息
message = 'This is a test message.'
print('sending "%s"' % message)
sock.sendall(message.encode())
# 循环接收数据
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(1024)
amount_received += len(data)
print('received "%s"' % data.decode())
finally:
# 清理连接
sock.close()
```
阅读全文