python tcp 服务端
时间: 2023-11-13 12:54:48 浏览: 94
python tcp服务端
4星 · 用户满意度95%
好的,以下是 Python TCP 服务端的代码示例:
```python
import socket
HOST = '127.0.0.1' # 监听的IP地址
PORT = 8888 # 监听的端口号
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind((HOST, PORT))
# 开始监听
server_socket.listen(1)
print('等待客户端连接...')
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print('客户端已连接:', client_address)
while True:
# 接收客户端发送的数据
data = client_socket.recv(1024)
if not data:
break
print('收到客户端消息:', data.decode())
# 发送响应数据给客户端
response = 'Hello, client!'
client_socket.sendall(response.encode())
# 关闭连接
client_socket.close()
server_socket.close()
```
阅读全文