本文整理汇总了Python中websocket_server.WebsocketServer.send_message_to_all方法的典型用法代码示例。如果您正苦于以下问题:Python WebsocketServer.send_message_to_all方法的具体用法?Python WebsocketServer.send_message_to_all怎么用?Python WebsocketServer.send_message_to_all使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类websocket_server.WebsocketServer
的用法示例。
在下文中一共展示了WebsocketServer.send_message_to_all方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_song_list
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import send_message_to_all [as 别名]
elif "songlist" in message:
r = {"action": "songlist", "data": get_song_list()}
server.send_message(client, json.dumps(r))
elif "delsong" in message:
try:
song = message[7:]
except Exception as e:
logging.error("Error in parsing raw message `delsong`. e: %s, trackback: %s" % (e, format_exc(e)))
else:
logging.info("Try del: %s" % song)
r = {"action": "songlist", "data": del_a_song(song)}
server.send_message_to_all(json.dumps(r))
if __name__ == "__main__":
server = WebsocketServer(8080, "haha5")
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
t = Thread(target=server.run_forever)
t.start()
mq = RedisMessageQueue()
while True:
msg = mq.accept_msg()
logging.info("Global message: %s" % msg)
response = {"action": "msg", "data": msg}
server.send_message_to_all(json.dumps(response))
示例2: __init__
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import send_message_to_all [as 别名]
class WSServer:
def __init__(self, port=9007):
self.port = port
self.server = WebsocketServer(self.port, host='0.0.0.0')
self.server.set_fn_new_client(self.on_connect)
self.server.set_fn_message_received(self.on_msg)
self.server.set_fn_client_left(self.on_disconnect)
self.msg_lock = Lock()
def ping(self):
self.server.send_message_to_all(json.dumps({'action': 'ping'}))
# pinging every 50 seconds to avoid disconnection
t = Timer(50, self.ping)
t.start()
def on_connect(self, client, server):
#server.send_message_to_all("Hey all, a new client has joined us")
pass
def on_disconnect(self, client, server):
#server.send_message_to_all("Hey all, a new client has joined us")
pass
def on_msg(self, client, server, message):
self.msg_lock.acquire()
try:
args = message.split(' ')
command = args[0]
args = args[1:]
internal = 'internal_ws_' + command
if hasattr(self, internal):
getattr(self, internal)(client, *args)
else:
data = {'action': 'cmd', 'msg': 'not found'}
self.server.send_message(client, json.dumps(data))
except Exception as e:
print("Error: ", e)
connection.close()
self.msg_lock.release()
def run(self):
self.ping()
self.server.run_forever()
def drop_seat(self, hold):
session = hold.session
layout = hold.layout
row, col = hold.seat.split('-')
data = {
'action': 'drop',
'session': session.id,
'layout': layout.id,
'row': row,
'col': col,
}
hold.delete()
confirmed = not session.is_seat_available(layout, row, col)
if confirmed:
data['action'] = 'confirm'
self.server.send_message_to_all(json.dumps(data))
def notify_confirmed(self):
d = timezone.now()
d = d - datetime.timedelta(seconds=80)
holds = TicketSeatHold.objects.filter(date__gt=d, type="R")
for h in holds:
row, col = h.seat.split('-')
data = {
'action': 'confirm',
'session': h.session.id,
'layout': h.layout.id,
'row': row,
'col': col,
}
self.server.send_message_to_all(json.dumps(data))
# Protocol definitions
def internal_ws_autoseats(self, client, session, amount, user):
session = Session.objects.get(id=session)
seats = search_seats(session, int(amount))
data = {
'action': 'autoseat',
'session': session.id,
'seats': seats,
}
for s in seats:
layout = SeatLayout.objects.get(id=s['layout'])
seat = '{}-{}'.format(s['row'], s['col'])
d2 = {
'action': 'hold',
'session': session.id,
#.........这里部分代码省略.........
示例3: WebsocketPublisher
# 需要导入模块: from websocket_server import WebsocketServer [as 别名]
# 或者: from websocket_server.WebsocketServer import send_message_to_all [as 别名]
#.........这里部分代码省略.........
self.timer = None
self.ws_server = WebsocketServer(port, host)
def send_to_client(client, server):
with self.lock:
server.send_message(client, self.build_graph(True))
self.ws_server.set_fn_new_client(send_to_client)
t = threading.Thread(target=self.ws_server.run_forever)
t.daemon = True
t.start()
def build_nodes(self, mon):
"""Builds a JSON representation of the CS nodes in the cluster."""
nodes = []
for cs in mon.cs.values():
nodes.append({"id": cs.id,
"name": cs.name,
"ip": cs.ip,
"load": (100*cs.active_jobs())/cs.maxjobs})
return json.dumps(nodes)
def build_links(self, mon):
"""
Builds a JSON representation of the links in the cluster.
There is one link A->B if A has one or more jobs building on B.
"""
links = []
for job in mon.jobs.values():
if job.host_id not in mon.cs or job.client_id not in mon.cs:
continue
c, s = mon.cs[job.client_id], mon.cs[job.host_id]
# Don't double-add links.
add = True
for l in links:
if l["source"] == c.id and l["target"] == s.id:
add = False
if add:
links.append({"source": c.id, "target": s.id, "value": 10})
return json.dumps(links)
def build_graph(self, full=False):
"""Builds a full JSON representation of a graph of the cluster."""
frame = '{"timestamp": 0, "index": 0'
if full or self.nodes != self.last_sent_nodes:
frame += ', "nodes": ' + self.nodes
if full or self.links != self.last_sent_links:
frame += ', "links": ' + self.links
frame += '}'
return frame
def publish(self, mon):
"""
Called by the Monitor to indicate new cluster state.
Update our internal state, and notify clients if appropriate.
"""
with self.lock:
self.nodes = self.build_nodes(mon)
self.links = self.build_links(mon)
self.frame = self.build_graph()
self.notify()
def notify(self):
"""Send updates to clients if necessary."""
now = time.time()
with self.lock:
if self.frame == self.last_sent_frame:
# Frame hasn't changed, don't resend.
return
elif (now >= self.next_time_to_send and self.timer is None):
# We can send.
self.broadcast()
elif self.timer is None:
# We must reschedule.
self.timer = threading.Timer(self.next_time_to_send - now,
self.broadcast)
self.timer.start()
def broadcast(self):
"""Actually broadcast cluster state to all connected clients."""
with self.lock:
if self.timer is not None:
self.timer.cancel()
self.timer = None
self.next_time_to_send = time.time() + self.MIN_SEND_GAP_S
self.last_sent_frame = self.frame
self.last_sent_nodes = self.nodes
self.last_sent_links = self.links
self.ws_server.send_message_to_all(self.frame)