def handle(self, packet): """Handle an incoming packet on this socket. Event: {'endpoint': u'', 'type': 'event', 'name': u'hi', 'args': [{u'hello': u'world'}]} Message: {'data': u'hi', 'endpoint': u'', 'type': 'message'} """ try: endpoint = packet["endpoint"] channel = None type = packet["type"] if type == "event": channel = packet["name"] message = packet["args"] events.on_event.send(self.request, self.socket, self.environ, channel, endpoint, message) elif type == "message": message = packet["data"] events.on_message.send(self.request, self.socket, self.environ, None, endpoint, message) else: # TODO :: Determine if there are other types we might see here. # TODO :: Client side connect/disconnect handled by # TODO :: recv_connect() and recv_disconnect() respectively. pass log_message = format_log(self.request, type, message) if log_message: # self.socket.handler.server.log.write(log_message) pass except Exception, exception: from traceback import print_exc print_exc() events.on_error.send(self.request, self.socket, self.environ, channel, exception)
def GET(self): """ Socket.IO handler - maintains the lifecycle of a Socket.IO request, sending the each of the events. Also handles adding/removing request/socket pairs to the CLIENTS dict which is used for sending on_finish events when the server stops. """ context = {} socket = SocketIOChannelProxy(web.ctx.env["socketio"]) request = web.ctx.env client_start(request, socket, context) try: if socket.on_connect(): events.on_connect.send(request, socket, context) while True: messages = socket.recv() if not messages and not socket.connected(): events.on_disconnect.send(request, socket, context) break messages = iter(messages) for message in messages: if message == "__subscribe__": message = messages.next() message_type = "subscribe" socket.subscribe(message) events.on_subscribe.send(request, socket, context, message) elif message == "__unsubscribe__": message = messages.next() message_type = "unsubscribe" socket.unsubscribe(message) events.on_unsubscribe.send(request, socket, context, message) else: # Socket.IO sends arrays as individual messages, so # they're put into an object in socketio_scripts.html # and given the __array__ key so that they can be # handled consistently in the on_message event. message_type = "message" if message == "__array__": message = messages.next() events.on_message.send(request, socket, context, message) log_message = format_log(request, message_type, message) if log_message: socket.handler.server.log.write(log_message) except Exception, exception: from traceback import print_exc print_exc() events.on_error.send(request, socket, context, exception)