本文整理匯總了Python中websocket_server.WebsocketServer.send_message方法的典型用法代碼示例。如果您正苦於以下問題:Python WebsocketServer.send_message方法的具體用法?Python WebsocketServer.send_message怎麽用?Python WebsocketServer.send_message使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類websocket_server.WebsocketServer
的用法示例。
在下文中一共展示了WebsocketServer.send_message方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: IPCWebSocket
# 需要導入模塊: from websocket_server import WebsocketServer [as 別名]
# 或者: from websocket_server.WebsocketServer import send_message [as 別名]
class IPCWebSocket(object):
def __init__(self, ipc):
self.ipc = ipc
self.server = WebsocketServer(9000)
self._set_callbacks(self.server)
self.clients = []
def start(self):
from threading import Thread
def run():
self.server.run_forever()
t = Thread(target=run)
t.daemon = True
t.start()
def _set_callbacks(self, server):
server.set_fn_new_client(self.on_connect)
server.set_fn_client_left(self.on_disconnect)
server.set_fn_message_received(self.on_message)
def on_connect(self, client, server):
print("New client connected")
self.clients.append(client)
def on_disconnect(self, client, server):
print("Client disconnected")
self.clients = [c for c in self.clients if c['id'] != client['id']]
def on_message(self, client, server, message):
message = json.loads(message)
self.ipc.on_message(client, message)
def broadcast(self, message):
message = json.dumps(message)
for c in self.clients:
self.server.send_message(c, message)
print("broadcasted message to {} clients".format(len(self.clients)))
def send(self, client, message):
self.server.send_message(client, json.dumps(message))
示例2: __init__
# 需要導入模塊: from websocket_server import WebsocketServer [as 別名]
# 或者: from websocket_server.WebsocketServer import send_message [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: WebSocket
# 需要導入模塊: from websocket_server import WebsocketServer [as 別名]
# 或者: from websocket_server.WebsocketServer import send_message [as 別名]
class WebSocket(Agent):
autostart = True
def __init__(self):
super(WebSocket, self).__init__()
self.target = self.identifier
self.server = WebsocketServer(5601, "0.0.0.0")
self.wsThread = threading.Thread(target=self.server.run_forever)
self.clients = self.server.clients
self.subscriptions = []
@self.server.set_fn_new_client
def new_client(client, server):
client["subscriptions"] = []
@self.server.set_fn_client_left
def client_left(client, server):
logging.info("Client(%d) disconnected" % client['id'])
@self.server.set_fn_message_received
def message_received(client, server, msg):
if msg:
try:
event = json.loads(msg)
event_type = event["type"]
event_data = event["data"]
if event_type == "subscribe":
self._subscribe(client, event_data)
elif event_type == "unsubscribe":
self._unsubscribe(client, msg)
else:
Dispatcher().put_event(Event(type=event_type, data=event_data))
except json.decoder.JSONDecodeError as e:
pass
def run(self):
self.wsThread.start()
self._listener()
def _listener(self):
while self.wsThread.isAlive():
event = self.next_event()
event_type = event["type"]
event_data = event["data"]
for client in self.clients:
if event_type in client["subscriptions"]:
self.server.send_message(client, json.dumps(event))
def _subscribe(self, client, event_data):
client["subscriptions"].append(str(event_data))
if not str(event_data) in self.subscriptions:
self.subscriptions.append(str(event_data))
Dispatcher().bind(self, event_data)
logging.info("Client subscribed to " + event_data)
def _unsubscribe(self, client, event_data):
if str(event_data) in client["subscriptions"]:
client["subscriptions"].remove(event_data)
othersubscriber = False
for otherclient in self.clients:
if str(event_data) in otherclient["subscriptions"]:
othersubscriber = True
if not othersubscriber:
self.subscriptions.remove(str(event_data))
logging.info("Client unsubscribed from " + event_data)
else:
# Client wasn't found in subscribers list
pass
示例4: connecting
# 需要導入模塊: from websocket_server import WebsocketServer [as 別名]
# 或者: from websocket_server.WebsocketServer import send_message [as 別名]
class websocketserver:
cameras = {}
tags = {}
users = {}
calibration = {}
port=8001
# Called for every client connecting (after handshake)
def new_client_connection(self, client, server):
print("New client connected and was given id %d" % client['id'] +" and address " + str(client['address']))
server.send_message(client, "Client connected succesfully")
# Called for every client disconnecting
def client_left(self, client, server):
print("Client(%d) disconnected" % client['id'])
# Remove client from its list
# TODO better delete (remove points etc...)
if(str(client['address']) in self.cameras):
print "Camera disconnected : " + str(client['address'])
del self.cameras[str(client['address'])]
elif(str(client['address']) in self.users):
# Remove Tag assignement because User left
print "User disconnected : " + str(client['address'])
self.users[str(client['address'])].removeTag()
del self.users[str(client['address'])]
elif(str(client['address']) in self.calibration):
print "Calibration disconnected : " + str(client['address'])
del self.calibration[str(client['address'])]
elif(str(client['address']) in self.tags):
print "Tag disconnected : " + str(client['address'])
# Remove Tag assignement to User because Tag left AND kill 3D point
for key in self.users:
if self.users[key].tag == self.tags[str(client['address'])]:
self.users[key].removeTag()
del self.tags[str(client['address'])]
# Called when a client sends a message
def message_received(self, client, server, message):
self.parseMessage(client, message)
def __init__(self, host='127.0.0.1'):
self.server = WebsocketServer(self.port, host)
self.server.set_fn_new_client(self.new_client_connection)
self.server.set_fn_client_left(self.client_left)
self.server.set_fn_message_received(self.message_received)
self.server.run_forever()
def parseMessage(self, client, message):
"""
Check who is the message from to redirect it to User / Tag / Camera / Calibration
or create a new instance of User / Tag / Camera / Calibration
:param client:
:param message:
:return:
"""
if self.cameras.has_key(str(client['address'])):
#print "Message from Camera"
self.cameras[str(client['address'])].push(message)
# Update all cameras counters
#Todo: Change this method for checking all cameras for lost point (auto check inside point2D ?)
for key in self.cameras.keys():
self.cameras[key].update()
elif self.users.has_key(str(client['address'])):
print "Message from User"
elif self.tags.has_key(str(client['address'])):
print "Message from Tag"
elif self.calibration.has_key(str(client['address'])):
self.calibration[str(client['address'])].push(message)
print "Message from Calibration"
# This message is coming from an unknown client
else:
if message.split("-")[0] == "camera":
self.cameras[str(client['address'])] = Camera(client, message.split("-")[1])
# Add Observers linking every user to every camera's update
for key in self.users:
if isinstance(self.users[key], User):
self.cameras[str(client['address'])].new2DPointNotifier.addObserver(self.users[key].position.newPoint2DObserver)
self.cameras[str(client['address'])].point2DdeletedNotifier.addObserver(self.users[key].position.point2DDeletedObserver)
elif message.split("-")[0] == "tag":
self.tags[str(client['address'])] = Tag(self.server, client, message.split("-")[1])
for key in self.users:
if isinstance(self.users[key], User):
# Assign a Tag to User with no Tag
if self.users[key].tag == None:
self.users[key].setTag(self.tags[str(client['address'])])
#.........這裏部分代碼省略.........