擅长:python、mysql、java
<p>我偶然发现了类似的问题。这是我的解决办法。希望这对外面的人有帮助</p>
<pre><code>wss = []
class wsHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'Online'
if self not in wss:
wss.append(self)
def on_close(self):
print 'Offline'
if self in wss:
wss.remove(self)
def wsSend(message):
for ws in wss:
ws.write_message(message)
</code></pre>
<p>要向WebSocket发送消息,只需使用以下命令:</p>
<pre><code>wsSend(message)
</code></pre>
<p><strong>wsSend更新</strong></p>
<p>我偶尔会遇到wsSend的例外。为了解决这个问题,我将代码修改为:</p>
<blockquote>
<pre><code>def wsSend(message):
for ws in wss:
if not ws.ws_connection.stream.socket:
print "Web socket does not exist anymore!!!"
wss.remove(ws)
else:
ws.write_message(message)
</code></pre>
</blockquote>