我目前正在尝试制作一个聊天室服务器。我正在努力做到这一点,以便我可以同时监听新请求的连接和监听从已建立的连接发送的消息。
我可以用它来监听请求的连接:
def reqlisten():
global hostlist
while True:
conn, address = (sock.accept)
hostlist.append(conn)
print 'Recieved connection form', address
我可以使用它来监听从已建立的连接发送的消息:
def meslisten():
global hostlist
while True:
ready_socks,_,_ = select.select(hostlist, [], [])
for sock in ready_socks:
data, addr = sock.recvfrom(255)
print 'Received message:', data
broadcast(message)
print 'Broadcasting message.'
但我如何同时进行这两项操作呢?
最佳答案
有多种方法可以做到这一点。
- 一种简单的方法是一次接受一个连接,并通过将套接字设置为异步非阻塞来在接受的套接字上接收固定数量的数据。
下面是执行此操作的示例代码。
hostlist = []
def Accept(sock):
##Accept one connection at a time
conn,address = sock.accept()
print "accept",address
conn.setblocking(0)
hostlist.append(conn)
def Recv(sock):
data,addr = sock.recvfrom(255)
print "recv",data
if __name__ == "__main__":
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.bind((socket.gethostname(),4041))
listen_socket.setblocking(0)
listen_socket.listen(5)
hostlist.append(listen_socket)
while True:
ready_socks,_,_ = select.select(hostlist, [], [])
for sock in ready_socks:
if sock == listen_socket:
Accept(sock)
else:
Recv(sock)
关于 python 2.7 : Listen to requested connections + listen to already established connections at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40980873/