Python tornado 模块,websocket() 实例源码

我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用tornado.websocket()

项目:bcloud    作者:xin1195    | 项目源码 | 文件源码
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 ?????
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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.")
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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)
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
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
项目:django-tornado-websockets    作者:Kocal    | 项目源码 | 文件源码
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
        })
项目:coretools    作者:iotile    | 项目源码 | 文件源码
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
项目:geoip-attack-map    作者:MatthewClarkMay    | 项目源码 | 文件源码
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)
项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
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
项目:ATX    作者:NetEaseGame    | 项目源码 | 文件源码
def open(self):
        print 'websocket connected'
        self.write_message(TestHandler.output)
        self.clients.add(self)
项目:geekcloud    作者:GeekCloud-Team    | 项目源码 | 文件源码
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
项目:AutomatorX    作者:xiaoyaojjian    | 项目源码 | 文件源码
def open(self):
        print 'websocket connected'
        self.write_message(TestHandler.output)
        self.clients.add(self)
项目:slidoc    作者:mitotic    | 项目源码 | 文件源码
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)
项目:GitAgent    作者:alexazhou    | 项目源码 | 文件源码
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)
项目:GitAgent    作者:alexazhou    | 项目源码 | 文件源码
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
项目:GitAgent    作者:alexazhou    | 项目源码 | 文件源码
def on_close(self):
        print("websocket close")
        del client_sockets[ str(id(self)) ]
项目:Platypus    作者:gmemstr    | 项目源码 | 文件源码
def open(self):
        AliveSockets.add(self)
        print("Fetch websocket opened - client " + self.request.remote_ip)
项目:Platypus    作者:gmemstr    | 项目源码 | 文件源码
def on_close(self):
        AliveSockets.remove(self)
        print("Fetch websocket closed - client " + self.request.remote_ip)
项目:server    作者:sgr-smile2015    | 项目源码 | 文件源码
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
项目:zynthian-webconf    作者:zynthian    | 项目源码 | 文件源码
def ZynthianWebSocketMessageHandlerFactory(handler_name, websocket):
    for cls in ZynthianWebSocketMessageHandler.__subclasses__():
        if cls.is_registered_for(handler_name):
            return cls(handler_name, websocket)
    raise ValueError
项目:zynthian-webconf    作者:zynthian    | 项目源码 | 文件源码
def __init__(self, handler_name, websocket):
        self.handler_name = handler_name
        self.websocket = websocket
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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))
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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)
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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))
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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!")
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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))
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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))
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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!")
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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.")
项目:multitude    作者:mesilliac    | 项目源码 | 文件源码
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)
项目:stock    作者:pythonstock    | 项目源码 | 文件源码
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)
项目:stock    作者:pythonstock    | 项目源码 | 文件源码
def on_close(self):
            # When the socket is closed, deregister the websocket with
            # the FigureManager.
            manager = self.application.manager
            manager.remove_web_socket(self)
项目:stock    作者:pythonstock    | 项目源码 | 文件源码
def on_message(self, message):
            # The 'supports_binary' message is relevant to the
            # websocket itself.  The other messages get passed along
            # to matplotlib as-is.

            # Every message has a "type" and a "figure_id".
            message = json.loads(message)
            if message['type'] == 'supports_binary':
                self.supports_binary = message['value']
            else:
                manager = self.application.manager
                manager.handle_json(message)
项目:audiosocket-demo    作者:nexmo-community    | 项目源码 | 文件源码
def __init__(self):
        # Browser websocket connections for receiving the binary audio data:
        self.clients = []
        # Browser websocket connections for receiving the event data:
        self.eventclients = []
        self.payload = None  # The buffered PCM frames into 200ms WAV file
        self.count = 0  # How many PCM frames I have in the buffer
        self.vapi_call_uuid = None
        self.vapi_connected = False
项目:audiosocket-demo    作者:nexmo-community    | 项目源码 | 文件源码
def connect_vapi(self):
        logging.info("Instructing VAPI to connect")
        response = client.create_call({'to': [{
                "type": "websocket",
                "uri": "ws://{host}/socket".format(host=CONFIG.host),
                "content-type": "audio/l16;rate=16000",
                "headers": {
                    "app": "audiosocket"
                }
            }],
            'from': {'type': 'phone', 'number': CONFIG.phone_number},
            'answer_url': ['https://{host}/ncco'.format(host=CONFIG.host)]})
        logging.debug(repr(response))
        self.vapi_connected = True
        return True
项目:django-tornado-websockets    作者:Kocal    | 项目源码 | 文件源码
def initialize(self, websocket):
        """
            Called when class initialization, makes a link between a :class:`~tornado_websockets.websocket.WebSocket`
            instance and this object.

            :param websocket: instance of WebSocket.
            :type websocket: WebSocket
        """

        # Make a link between a WebSocket instance and this object
        self.websocket = websocket
        websocket.handlers.append(self)
项目:django-tornado-websockets    作者:Kocal    | 项目源码 | 文件源码
def open(self):
        """
            Called when the WebSocket is opened
        """

        for event in self.websocket.events:
            if event.endswith('open'):
                self.on_message('{"event": "%s", "data": {}}' % event)
项目:django-tornado-websockets    作者:Kocal    | 项目源码 | 文件源码
def on_message(self, message):
        """
            Handle incoming messages on the WebSocket.

            :param message: JSON string
            :type message: str
        """

        try:
            message = tornado.escape.json_decode(message)
            event = message.get('event')
            data = message.get('data')
        except ValueError:
            self.emit_warning('Invalid JSON was sent.')
            return

        if not event:
            self.emit_warning('There is no event in this JSON.')
            return

        if not self.websocket.events.get(event):
            return

        if not data:
            data = {}
        elif not isinstance(data, dict):
            self.emit_warning('The data should be a dictionary.')
            return

        callback = self.websocket.events.get(event)
        spec = inspect.getargspec(callback)
        kwargs = {}

        if 'self' in spec.args:
            kwargs['self'] = self.websocket.context
        if 'socket' in spec.args:
            kwargs['socket'] = self
        if 'data' in spec.args:
            kwargs['data'] = data

        return callback(**kwargs)
项目:django-tornado-websockets    作者:Kocal    | 项目源码 | 文件源码
def on_close(self):
        """
            Called when the WebSocket is closed, delete the link between this object and its WebSocket.
        """

        self.websocket.handlers.remove(self)
项目:jumpsever    作者:jacksonyoudi    | 项目源码 | 文件源码
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
项目:coretools    作者:iotile    | 项目源码 | 文件源码
def on_message(self, message):
        """Handle a message received on the websocket."""
        cmd = self.unpack(message)

        try:
            CommandMessage.verify(cmd)
            self._on_command(cmd)
        except ValidationError:
            if 'operation' in cmd:
                self.logger.exception("Invalid operation received: %s", cmd['operation'])

            self.send_error('message did not correspond with a known schema')
项目:coretools    作者:iotile    | 项目源码 | 文件源码
def send_response(self, success, obj):
        """Send a response back to someone."""

        resp_object = {'type': 'response', 'success': success}
        if obj is not None:
            resp_object['payload'] = obj

        msg = msgpack.packb(resp_object, default=self.encode_datetime)
        self.logger.debug("Sending response: %s", obj)
        try:
            self.write_message(msg, binary=True)
        except tornado.websocket.WebSocketClosedError:
            pass
项目:coretools    作者:iotile    | 项目源码 | 文件源码
def send_error(self, reason):
        """Send an error to someone."""

        msg = msgpack.packb({'type': 'response', 'success': False, 'reason': reason})

        try:
            self.logger.debug("Sending error: %s", reason)
            self.write_message(msg, binary=True)
        except tornado.websocket.WebSocketClosedError:
            pass
项目:tensorspark    作者:adatao    | 项目源码 | 文件源码
def test_ws_1():
    client = yield tornado.websocket.websocket_connect("ws://localhost:8888/")
    for i in range (10):
        client.write_message('1')
        msg = yield client.read_message()
        print msg
项目:tensorspark    作者:adatao    | 项目源码 | 文件源码
def test_ws_2():
    client = yield tornado.websocket.websocket_connect("ws://localhost:8888/")
    for i in range (10):
        client.write_message('2')
        msg = yield client.read_message()
        print msg
项目:funcserver    作者:deep-compute    | 项目源码 | 文件源码
def define_log_pre_format_hooks(self):
        """
        adds a hook to send to websocket if the run command was selected
        """
        hooks = super(Server, self).define_log_pre_format_hooks()
        # NOTE enabling logs only on debug mode
        if self.args.func == self.run and self.args.debug:
            hooks.append(self._send_log_to_ws)

        return hooks
项目:SonOTA    作者:mirko    | 项目源码 | 文件源码
def on_close(self):
        log.debug("~~ websocket close")
项目:SDPremote    作者:MartinBienz    | 项目源码 | 文件源码
def writetldirs(handler):
    mydirs=gettldirs(timelapsedir)

    content=[]

    for item in mydirs:

        fcount = len([name for name in os.listdir(item) if os.path.isfile(os.path.join(item,name))])
        totsize = helpers.bytes2human(sum(os.path.getsize(os.path.join(item,name)) for name in os.listdir(item) if os.path.isfile(os.path.join(item,name))))

        if not fcount == 0:
            thumbnail=sorted([ name for name in os.listdir(item) if os.path.isfile(os.path.join(item,name))])[-1]
        else:
            thumbnail="../../images/nocam.png"

        info = {
        "directory":    item,
        "count": fcount,
        "size":  totsize,
        "thumbnail": thumbnail,
        }
        content.append(info)

    handler.write(json.dumps({"info": content}))

#webserver------------------------------------------------------------------------------------------------------------
#WebsocketHandler HTML5 and other websocket capable clients