用python3.6写一个TCPsever 服务
时间: 2024-02-27 08:54:10 浏览: 86
好的,以下是一个简单的 Python3.6 TCP 服务器代码实现,可以监听本地 9999 端口并接收来自客户端的消息:
```python
import socket
server_host = 'localhost'
server_port = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_host, server_port))
server_socket.listen(1)
print('Listening on port %s ...' % server_port)
while True:
client_conn, client_addr = server_socket.accept()
print('Accepted connection from %s:%d' % (client_addr[0], client_addr[1]))
while True:
data = client_conn.recv(1024)
if not data:
break
print('Received from %s:%d: %s' % (client_addr[0], client_addr[1], data.decode('utf-8')))
client_conn.sendall(data)
client_conn.close()
print('Connection closed by %s:%d' % (client_addr[0], client_addr[1]))
```
你可以将以上代码保存为 server.py 并在命令行中执行 `python server.py` 来启动 TCP 服务器。
阅读全文