如何创建一个简单的Python echo服务器来记住客户端,而不是为每个请求创建一个新的套接字?必须能够支持并发访问。我希望能够连接一次并使用此客户端或类似程序不断发送和接收数据:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("Server hostname or ip? ")
port = input("Server port? ")
sock.connect((host,port))
while True:
data = raw_input("message: ")
sock.send(data)
print "response: ", sock.recv(1024)
即。如果服务器在端口50000上运行,使用上面的客户端我希望能够这样做:
me@mine:~$ client.py
Server hostname or ip? localhost
Server Port? 50000
message: testa
response: testa
message: testb
response: testb
message: testc
response: testc
答案 0 :(得分:66)
您可以为每个客户端使用一个线程来避免阻塞client.recv()
,然后使用主线程来监听新客户端。当一个连接时,主线程创建一个新线程,它只是监听新客户端,并在它不通话60秒时结束。
import socket
import threading
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
# Set the response to echo back the recieved data
response = data
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
if __name__ == "__main__":
while True:
port_num = input("Port? ")
try:
port_num = int(port_num)
break
except ValueError:
pass
ThreadedServer('',port_num).listen()
客户端在60秒不活动后超时,必须重新连接。请参阅函数client.settimeout(60)
ThreadedServer.listen()