def open(self):
device_id = str(self.get_argument("device_id"))
# ????
ApiDeviceSocketHandler.send_success(self)
logging.info("device_id: " + device_id + " : connect_success")
# ??????????
ApiDeviceSocketHandler.device_client_map[device_id] = self
logging.info("device_client_map: " + str(ApiDeviceSocketHandler.device_client_map))
# ???????
playlist = BaseFunctionHandler.get_res_group_by_device_id(device_id)
self.write_message(json.dumps(playlist))
logging.info(device_id + '????????:' + str(json.dumps(playlist)))
# ?????????
time_switch = BaseFunctionHandler.get_time_switch(device_id)
self.write_message(json.dumps(time_switch))
logging.info(device_id + '?????????:' + str(json.dumps(time_switch)))
# ??websocket ?????
python类websocket()的实例源码
def on_message(self, message):
"""Called when a websocket client sends a message."""
# print the message to the console
print("client sent: {!r}".format(message))
# try to parse the message
try:
parsed_message = json.loads(message)
except ValueError:
print("Failed to parse message: {!r}".format(message))
return
# if there's a "message" in the message, echo it
if "message" in parsed_message:
response = {
"client" : str(self.request.remote_ip),
"message" : parsed_message["message"]
}
# respond to the message
m = json.dumps(response)
self.write_message(m)
else:
print("message unhandled.")
def open(self):
"""Called when a websocket connection is initiated."""
# print some info about the opened connection
print("WebSocket opened",
"from user at {}".format(self.request.remote_ip))
# add this connection to the set of active connections
client_connections.add(self)
# assign a random not-too-light colour
self.color = '#'
for i in range(3):
self.color += hex(random.randint(0,13))[2:]
# assign a nickname
self.nickname = str(self.request.remote_ip)
def _gc(self):
"""Remove disconnected websocket handlers."""
for directory in self.handlers.keys():
handlers = [(pattern, handler, impl)
for pattern, handler, impl in self.handlers[directory]
if handler.active()]
_LOGGER.info('Number of active handlers for %s: %s',
directory, len(handlers))
if not handlers:
_LOGGER.info('No active handlers for %s', directory)
self.handlers.pop(directory, None)
if directory not in self.watch_dirs:
# Watch is not permanent, remove dir from watcher.
self.watcher.remove_dir(directory)
else:
self.handlers[directory] = handlers
def emit(self, event, data):
"""
Sends a given event/data combinaison to the client of this WebSocket.
Wrapper for `tornado.websocket.WebSocketHandler.write_message <http://www.tornadoweb.org/en/stable/
websocket.html#tornado.websocket.WebSocketHandler.write_message>`_ method.
:param event: event name to emit
:param data: associated data
:type event: str
:type data: dict
"""
self.write_message({
'event': event,
'data': data
})
def send_notification(self, name, change_type, change_info, directed_client=None):
"""Send an unsolicited notification to someone."""
# If the notification is directed, make sure it is directed at us
if directed_client is not None and self.client_id != directed_client:
return
notif_object = {'type': 'notification', 'operation': change_type, 'name': name}
if change_info is not None:
notif_object['payload'] = change_info
msg = msgpack.packb(notif_object)
try:
self.write_message(msg, binary=True)
except tornado.websocket.WebSocketClosedError:
pass
def main():
# Register handler pages
handlers = [
(r'/websocket', WebSocketChatHandler),
(r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
(r'/flags/(.*)', tornado.web.StaticFileHandler, {'path': 'static/flags'}),
(r'/', IndexHandler)
]
# Define the static path
#static_path = path.join( path.dirname(__file__), 'static' )
# Define static settings
settings = {
#'static_path': static_path
}
# Create and start app listening on port 8888
try:
app = tornado.web.Application(handlers, **settings)
app.listen(8888)
print('[*] Waiting on browser connections...')
tornado.ioloop.IOLoop.instance().start()
except Exception as appFail:
print(appFail)
def require_auth(role='user'):
def _deco(func):
def _deco2(request, *args, **kwargs):
if request.get_cookie('sessionid'):
session_key = request.get_cookie('sessionid')
else:
session_key = request.get_argument('sessionid', '')
logger.debug('Websocket: session_key: %s' % session_key)
if session_key:
session = get_object(Session, session_key=session_key)
logger.debug('Websocket: session: %s' % session)
if session and datetime.datetime.now() < session.expire_date:
user_id = session.get_decoded().get('_auth_user_id')
request.user_id = user_id
user = get_object(User, id=user_id)
if user:
logger.debug('Websocket: user [ %s ] request websocket' % user.username)
request.user = user
if role == 'admin':
if user.role in ['SU', 'GA']:
return func(request, *args, **kwargs)
logger.debug('Websocket: user [ %s ] is not admin.' % user.username)
else:
return func(request, *args, **kwargs)
else:
logger.debug('Websocket: session expired: %s' % session_key)
try:
request.close()
except AttributeError:
pass
logger.warning('Websocket: Request auth failed.')
return _deco2
return _deco
def open(self):
print 'websocket connected'
self.write_message(TestHandler.output)
self.clients.add(self)
def require_auth(role='user'):
def _deco(func):
def _deco2(request, *args, **kwargs):
if request.get_cookie('sessionid'):
session_key = request.get_cookie('sessionid')
else:
session_key = request.get_argument('sessionid', '')
logger.debug('Websocket: session_key: %s' % session_key)
if session_key:
session = get_object(Session, session_key=session_key)
logger.debug('Websocket: session: %s' % session)
if session and datetime.datetime.now() < session.expire_date:
user_id = session.get_decoded().get('_auth_user_id')
request.user_id = user_id
user = get_object(User, id=user_id)
if user:
logger.debug('Websocket: user [ %s ] request websocket' % user.username)
request.user = user
if role == 'admin':
if user.role in ['SU', 'GA']:
return func(request, *args, **kwargs)
logger.debug('Websocket: user [ %s ] is not admin.' % user.username)
else:
return func(request, *args, **kwargs)
else:
logger.debug('Websocket: session expired: %s' % session_key)
try:
request.close()
except AttributeError:
pass
logger.warning('Websocket: Request auth failed.')
return _deco2
return _deco
def open(self):
print 'websocket connected'
self.write_message(TestHandler.output)
self.clients.add(self)
def handover_connection(self, handover):
# Handover connection
##print >> sys.stderr, "DEBUG handover_connection", handover, self.pipeline.host_spec, self.pipeline.relay_address
external_stream = self.read_stream
# Shutdown pipeline; pretend it is an external shutdown
self.pipeline.shutdown(external=True)
if handover == "localhandler":
http_connection = httpserver.HTTPConnection(external_stream,
self.pipeline.from_address,
self.local_request_callback,
xheaders=self.pipeline.xheaders)
return
assert isinstance(self.pipeline.relay_address, tuple)
host, port = self.pipeline.relay_address
port += self.pipeline.multiplex_params[1]
self.proxy_connection_id = self.pipeline.proxy_server.proxy_id + "," + ("%s:%s" % (host, port))
# Setup connection
conn = self.pipeline.multiplex_params[0].get_client(self.proxy_connection_id,
connect=(host, port))
if handover == "websocket":
http_connection = httpserver.HTTPConnection(external_stream,
self.pipeline.from_address,
self.ws_request_callback,
xheaders=self.pipeline.xheaders)
def console_output(self,s):
print('console [%s]>>'%self.console_id,s )
if self.console_id != None:
try:
ws_cocket = client_sockets[ self.console_id ]
msg = {}
msg['type'] = 'output'
msg['content'] = s
ws_cocket.write_message( msg )
except Exception as e:
print('write to websocket failed:',e)
def open(self):
print("websocket open")
self.write_message(json.dumps({
'type': 'sys',
'message': 'Welcome to WebSocket',
'id': str(id(self)),
}))
client_sockets[ str(id(self)) ] = self
def on_close(self):
print("websocket close")
del client_sockets[ str(id(self)) ]
def open(self):
AliveSockets.add(self)
print("Fetch websocket opened - client " + self.request.remote_ip)
def on_close(self):
AliveSockets.remove(self)
print("Fetch websocket closed - client " + self.request.remote_ip)
def require_auth(role='user'):
def _deco(func):
def _deco2(request, *args, **kwargs):
if request.get_cookie('sessionid'):
session_key = request.get_cookie('sessionid')
else:
session_key = request.get_argument('sessionid', '')
logger.debug('Websocket: session_key: %s' % session_key)
if session_key:
session = get_object(Session, session_key=session_key)
logger.debug('Websocket: session: %s' % session)
if session and datetime.datetime.now() < session.expire_date:
user_id = session.get_decoded().get('_auth_user_id')
request.user_id = user_id
user = get_object(User, id=user_id)
if user:
logger.debug('Websocket: user [ %s ] request websocket' % user.username)
request.user = user
if role == 'admin':
if user.role in ['SU', 'GA']:
return func(request, *args, **kwargs)
logger.debug('Websocket: user [ %s ] is not admin.' % user.username)
else:
return func(request, *args, **kwargs)
else:
logger.debug('Websocket: session expired: %s' % session_key)
try:
request.close()
except AttributeError:
pass
logger.warning('Websocket: Request auth failed.')
return _deco2
return _deco
def ZynthianWebSocketMessageHandlerFactory(handler_name, websocket):
for cls in ZynthianWebSocketMessageHandler.__subclasses__():
if cls.is_registered_for(handler_name):
return cls(handler_name, websocket)
raise ValueError
def __init__(self, handler_name, websocket):
self.handler_name = handler_name
self.websocket = websocket
def open(self):
"""Called when a websocket connection is initiated."""
# print some info about the opened connection
print("WebSocket opened",
"from user at {}".format(self.request.remote_ip))
def on_message(self, message):
"""Called when a websocket client sends a message."""
# print the message to the console
print("client sent: {!r}".format(message))
# respond to the message
response = {"popup" : "Hello, client!"}
m = json.dumps(response)
self.write_message(m)
def open(self):
"""Called when a websocket connection is initiated."""
# print some info about the opened connection
print("WebSocket opened",
"from user at {}".format(self.request.remote_ip))
def on_message(self, message):
"""Called when a websocket client sends a message."""
# print the message to the console
print("client sent: {!r}".format(message))
# respond to the message
self.write_message("Hello, client!")
def open(self):
"""Called when a websocket connection is initiated."""
# print some info about the opened connection
print("WebSocket opened",
"from user at {}".format(self.request.remote_ip))
def open(self):
"""Called when a websocket connection is initiated."""
# print some info about the opened connection
print("WebSocket opened",
"from user at {}".format(self.request.remote_ip))
def on_message(self, message):
"""Called when a websocket client sends a message."""
# print the message to the console
print("client sent: {!r}".format(message))
# respond to the message
self.write_message("Hello, client!")
def on_message(self, message):
"""Called when a websocket client sends a message."""
# print the message to the console
print("client sent: {!r}".format(message))
# try to parse the message
try:
parsed_message = json.loads(message)
except ValueError:
print("Failed to parse message: {!r}".format(message))
return
# if there's a "message" in the message, echo it to everyone
if "message" in parsed_message:
if parsed_message["message"].startswith("/nick "):
self.nickname = parsed_message["message"].split()[1]
return
response = {
"client" : self.nickname,
"color" : self.color,
"message" : parsed_message["message"]
}
# respond to the message
m = json.dumps(response)
for connection in client_connections:
connection.write_message(m)
print("messaged {} clients".format(len(client_connections)))
else:
print("message unhandled.")
def on_message(self, message):
"""Called when a websocket client sends a message."""
# print the message to the console
print("client sent: {!r}".format(message))
# try to parse the message
try:
parsed_message = json.loads(message)
except ValueError:
print("Failed to parse message: {!r}".format(message))
return
# handle the message
self.handle_message(parsed_message)
def open(self):
# Register the websocket with the FigureManager.
manager = self.application.manager
manager.add_web_socket(self)
if hasattr(self, 'set_nodelay'):
self.set_nodelay(True)