python TCP服务端接收多个客户端数据的程序
时间: 2023-06-04 17:08:23 浏览: 254
可以通过多线程或者异步IO实现TCP服务端接收多个客户端数据,以下是一个基于多线程的示例程序:
```python
import socket
import threading
def handle_client(client_socket):
while True:
data = client_socket.recv(1024)
if not data:
break
# 处理客户端数据
response = b"Hello, client!"
client_socket.send(response)
client_socket.close()
def run_server():
host = "127.0.0.1"
port = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Listening on {host}:{port}...")
while True:
client_socket, client_address = server_socket.accept()
print(f"Accepted connection from {client_address[0]}:{client_address[1]}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
if __name__ == "__main__":
run_server()
```
此程序会监听本地8888端口,处每个客户端连接会启动一个新的线程来处理客户端数据。
阅读全文