python类websocket()的实例源码

apiWebSocket.py 文件源码 项目:bcloud 作者: xin1195 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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 ?????
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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.")
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:treadmill 作者: Morgan-Stanley 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
websockethandler.py 文件源码 项目:django-tornado-websockets 作者: Kocal 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
        })
ws_handler.py 文件源码 项目:coretools 作者: iotile 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
AttackMapServer.py 文件源码 项目:geoip-attack-map 作者: MatthewClarkMay 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
run_server.py 文件源码 项目:geekcloud 作者: Mr-Linus 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
web.py 文件源码 项目:ATX 作者: NetEaseGame 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def open(self):
        print 'websocket connected'
        self.write_message(TestHandler.output)
        self.clients.add(self)
run_server.py 文件源码 项目:geekcloud 作者: GeekCloud-Team 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
web.py 文件源码 项目:AutomatorX 作者: xiaoyaojjian 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def open(self):
        print 'websocket connected'
        self.write_message(TestHandler.output)
        self.clients.add(self)
multiproxy.py 文件源码 项目:slidoc 作者: mitotic 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
agent.py 文件源码 项目:GitAgent 作者: alexazhou 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
agent.py 文件源码 项目:GitAgent 作者: alexazhou 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
agent.py 文件源码 项目:GitAgent 作者: alexazhou 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def on_close(self):
        print("websocket close")
        del client_sockets[ str(id(self)) ]
Aor.py 文件源码 项目:Platypus 作者: gmemstr 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def open(self):
        AliveSockets.add(self)
        print("Fetch websocket opened - client " + self.request.remote_ip)
Aor.py 文件源码 项目:Platypus 作者: gmemstr 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def on_close(self):
        AliveSockets.remove(self)
        print("Fetch websocket closed - client " + self.request.remote_ip)
run_server.py 文件源码 项目:server 作者: sgr-smile2015 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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_websocket_handler.py 文件源码 项目:zynthian-webconf 作者: zynthian 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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_websocket_handler.py 文件源码 项目:zynthian-webconf 作者: zynthian 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, handler_name, websocket):
        self.handler_name = handler_name
        self.websocket = websocket
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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))
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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))
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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!")
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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))
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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))
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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!")
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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.")
server.py 文件源码 项目:multitude 作者: mesilliac 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
demo-chart.py 文件源码 项目:stock 作者: pythonstock 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号