任何人都可以帮助解决以下问题的代码
Write a multi-threaded Echo Handler in Python.
每个线程应该能够处理来自客户端的连接,而其他线程同时处理来自其他客户端的连接。要进行测试,请使用 time.sleep() 调用来确保并发性。使用 3 到 5 个线程。每个线程应该处理不同的端口号。
我尝试了以下代码:
` #!/usr/bin/python
import socket
import thread
import time
def Child_thread(clientsocket, (ip,port), id ):
data = "anonymous data"
print "Client with ID %d is now alive" %id
while len(data) > 0:
data = clientsocket.recv(2048)
print "data received from client with ID %d" %id
print "Data recieved is %s" %data
clientsocket.send(data)
print "Closing the connection.... of client with ID %d" %id
print "and port number %d" %port
clientsocket.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind( ("0.0.0.0", 8001) )
sock.listen(2)
for i in range(5):
print "Server is listening for clients"
(clientsocket, (ip,port) ) = sock.accept()
print "received connection from %s" %ip
print "Received connection from port number %d" %port
print "Starting Echo Server"
thread.start_new_thread(Child_thread, (clientsocket, (ip,port), (i,)))
time.sleep(10)
print "Server is shutting down"
sock.close()`