擅长:python、mysql、java
<blockquote>
<p>is [there] another way to send clients message from outside of server class?</p>
</blockquote>
<p>我这样做是为了传递信息。我使用<code>twisted</code>运行我的web应用程序。在</p>
<pre><code>import json
from autobahn.twisted.websocket import WebSocketServerProtocol
from twisted.internet import reactor
class MyProtocol(WebSocketServerProtocol):
connections = list()
def onConnect(self, request):
self.connections.append(self)
def onClose(self, wasClean, code, reason):
self.connections.remove(self)
@classmethod
def broadcast_message(cls, data):
payload = json.dumps(data, ensure_ascii = False).encode('utf8')
for c in set(cls.connections):
reactor.callFromThread(cls.sendMessage, c, payload)
# Somewhere else
MyProtocol.broadcast_message({'greeting': 'Hello world'})
</code></pre>
<p>我不知道这是否正确™,但对我来说效果很好。在</p>