我目前正在尝试制作一个聊天室服务器。我试图这样做,这样我就可以监听新请求的连接并同时监听已建立的连接发送的消息。
我可以用它来监听请求的连接:
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.'
但我如何同时做这两件事?
答案 0 :(得分:1)
有多种方法可以做到这一点。
下面是一个示例代码。
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)