本文介绍了WebSocket使用Python向所有客户端广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个基于Python的简单Web套接字应用程序:
I am using a simple Python based web socket application:
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
class SimpleEcho(WebSocket):
def handleMessage(self):
if self.data is None:
self.data = ''
# echo message back to client
self.sendMessage(str(self.data))
def handleConnected(self):
print self.address, 'connected'
def handleClose(self):
print self.address, 'closed'
server = SimpleWebSocketServer('', 8000, SimpleEcho)
server.serveforever()
它回显每个客户端发送到同一客户端的消息,但是II正在尝试将ws服务器收到的任何消息发送到与其连接的所有客户端。有人可以帮我吗?
It echoes messages sent by each client to the same individual client, but I I am trying to send any message received by the ws server to all clients connected to it. Can someone help me please?
推荐答案
或者您可以这样做:
class SimpleEcho(WebSocket):
def handleMessage(self):
if self.data is None:
self.data = ''
for client in self.server.connections.itervalues():
client.sendMessage(str(self.address[0]) + ' - ' + str(self.data))
#echo message back to client
#self.sendMessage(str(self.data))
def handleConnected(self):
print self.address, 'connected'
def handleClose(self):
print self.address, 'closed'
这篇关于WebSocket使用Python向所有客户端广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!