用python写一个tcp服务端
时间: 2024-05-14 09:12:16 浏览: 55
python tcp服务端
4星 · 用户满意度95%
以下是一个简单的TCP服务器示例:
```
import socket
# 创建一个TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 开始监听连接请求
server_socket.listen(1)
print('Server is listening on {}:{}'.format(*server_address))
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print('Received connection from {}:{}'.format(*client_address))
try:
# 接收客户端发送的数据
data = client_socket.recv(1024)
print('Received data from client: {}'.format(data))
# 向客户端发送响应
response = b'Hello, client!'
client_socket.sendall(response)
except Exception as e:
print('Error occurred while processing client request: ', e)
finally:
# 关闭客户端连接
client_socket.close()
```
此示例监听端口8888,接受客户端连接并返回“Hello, client!”响应。注意,此示例仅用于演示目的,实际服务器需要更复杂的逻辑来处理客户端请求。
阅读全文