我在运行 Flask 的服务器上使用 Flask-Socketio,我的客户端运行 javascript。我所有的客户端都使用 namespace 连接到服务器'/test'
。在客户端执行某个操作后,我希望客户端触发服务器上的一个函数,该函数遍历所有连接的客户端。我正在使用以下代码段来遍历连接的客户端列表:
for sessid, socket in request.namespace.socket.server.sockets.items():
print "socket id : %r" % (socket['/test'].session['id'])
每个连接都有一个在连接时分配给它的“id”键。
但是,有时服务器会给出以下错误,表明未找到命名空间键:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 327, in run
result = self._run(*self.args, **self.kwargs)
File "/usr/local/lib/python2.7/dist-packages/socketio/virtsocket.py", line 403, in_receiver_loop
retval = pkt_ns.process_packet(pkt)
File "/usr/local/lib/python2.7/dist-packages/socketio/namespace.py", line 155, in process_packet
return self.process_event(packet)
File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 64, in process_event
return self.socketio._dispatch_message(app, self, message, args)
File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 137, in _dispatch_message
ret = self.messages[namespace.ns_name][message](*args)
File "/home/ubuntu/flask-app/current/py/flaskapp/main/sockets.py", line 190, in gameInitialisedByClient
print "id : %r random: %r" % (socket['/test'].session['id'], socket['/test'].session['random'])
File "/usr/local/lib/python2.7/dist-packages/socketio/virtsocket.py", line 190, in __getitem__
return self.active_ns[key]
KeyError: '/test'
<Greenlet at 0x7f483bc6bf50: <bound method Socket._receiver_loop of <socketio.virtsocket.Socket object at 0x7f483a5ac6d0>>> failed with KeyError
我不明白为什么会出现此错误,因为我所有连接到服务器的套接字都连接在同一个命名空间上。此外,仅在一小部分函数调用期间会遇到此错误。为什么这个错误不一致?
有没有更好的方法可以遍历连接的客户端列表?