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

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

项目:upstox-python    作者:upstox    | 项目源码 | 文件源码
def start_websocket(self, run_in_background=False):
        socket_params = {}
        try:
            socket_params = self.get_socket_params()
        except requests.exceptions.HTTPError:
            print ("Can't Access Socket Params")
        ping_interval = 60
        ping_timeout = 10

        if 'pythonPingInterval' in socket_params.keys():
            ping_interval = socket_params['pythonPingInterval']

        if 'pythonPingTimeout' in socket_params.keys():
            ping_timeout = socket_params['pythonPingTimeout']

        url = self.config['socketEndpoint'].format(api_key=self.api_key, access_token=self.access_token)
        self.websocket = websocket.WebSocketApp(url,
                                                header={'Authorization: Bearer' + self.access_token},
                                                on_data=self._on_data,
                                                on_error=self._on_error,
                                                on_close=self._on_close)
        if run_in_background is True:
            self.ws_thread = threading.Thread(target=self.websocket.run_forever)
            self.ws_thread.daemon = True
            self.ws_thread.start()
        else:
            self.websocket.run_forever(ping_interval=ping_interval, ping_timeout=ping_timeout)
项目:cli    作者:sparkl    | 项目源码 | 文件源码
def __init__(self, args, ws_url):
        """
        Opens the websocket url.
        """
        self.args = args
        self.ws_url = ws_url
        self.on_message = lambda args, data: None
        cookies = unpickle_cookies(args)
        session = cookies["ipaas_session"]

        self.ws_connection = websocket.WebSocketApp(
            ws_url,
            on_message=self.__ws_message,
            on_open=self.__ws_open,
            on_error=self.__ws_error,
            on_close=self.__ws_close,
            on_data=self.__ws_data,
            cookie="ipaas_session=" + session)
项目:Cloudroid    作者:cyberdb    | 项目源码 | 文件源码
def run(self):
        self.topic_type = wait_topic_ready(self.topic_name, self.url)
    #print str(self.topic_type)+"  self.topic_type"
        if not self.topic_type:
            rospy.logerr('Type of topic %s are not equal in the remote and local sides', self.topic_name)
            return

        topic_type_module, topic_type_name = tuple(self.topic_type.split('/'))
        try:       
            roslib.load_manifest(topic_type_module)
            msg_module = import_module(topic_type_module + '.msg')
            self.rostype = getattr(msg_module, topic_type_name)

            if self.test:
                self.publisher = rospy.Publisher(self.topic_name + '_rb', self.rostype, queue_size = self.queue_size)
            else: 
                self.publisher = rospy.Publisher(self.topic_name, self.rostype, queue_size = self.queue_size)

            self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
            rospy.loginfo('Create connection to Rosbridge server %s for subscribed topic %s successfully', self.url, self.topic_name)
            self.ws.run_forever()
        except ResourceNotFound, e:
            rospy.logerr('Proxy for subscribed topic %s init falied. Reason: Could not find the required resource: %s', self.topic_name, str(e))
        except Exception, e:
            rospy.logerr('Proxy for subscribed topic %s init falied. Reason: %s', self.topic_name, str(e))
项目:Cloudroid    作者:cyberdb    | 项目源码 | 文件源码
def run(self):
        self.service_type, self.service_args = wait_service_ready(self.service_name, self.url)
        if not self.service_type:
            rospy.logerr('Type of service %s are not equal in the remote and local sides', self.service_type)
            return

        service_type_module, service_type_name = tuple(self.service_type.split('/'))
        try:       
            roslib.load_manifest(service_type_module)
            msg_module = import_module(service_type_module + '.srv')
            self.srvtype = getattr(msg_module, service_type_name)

            if self.test:
                self.caller = rospy.Service(self.service_name + '_rb', self.srvtype, self.callback)#, self.queue_size)
            else: 
                self.caller = rospy.Service(self.service_name, self.srvtype, self.callback)#, self.queue_size)

            self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
            rospy.loginfo('Create connection to Rosbridge server %s for calling service %s successfully', self.url, self.service_name)
            self.ws.run_forever()
        except ResourceNotFound, e:
            rospy.logerr('Proxy for service %s init falied. Reason: Could not find the required resource: %s', self.service_name, str(e))
        except Exception, e:
            rospy.logerr('Proxy for service %s init falied. Reason: %s', self.service_name, str(e))
项目:Cloudroid    作者:cyberdb    | 项目源码 | 文件源码
def run(self):
        self.topic_type = wait_topic_ready(self.topic_name, self.url)
        if not self.topic_type:
            rospy.logerr('Type of topic %s are not equal in the remote and local sides', self.topic_name)
            return

        topic_type_module, topic_type_name = tuple(self.topic_type.split('/'))
        try:      
            roslib.load_manifest(topic_type_module)
            msg_module = import_module(topic_type_module + '.msg')
            self.rostype = getattr(msg_module, topic_type_name)

            self.subscriber = rospy.Subscriber(self.topic_name, self.rostype, self.callback)

            self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
            rospy.loginfo('Create connection to Rosbridge server for published topic %s successfully', self.topic_name)
            self.ws.run_forever()
        except ResourceNotFound, e:
            rospy.logerr('Could not find the required resource %s', str(e))
        except Exception, e:
            rospy.logerr('Proxy for published topic %s init falied. Reason: %s', self.topic_name, str(e))
项目:rancher-gen    作者:pitrho    | 项目源码 | 文件源码
def start(self):
        header = {
            'Authorization': 'Basic {0}'.format(self.api_token)
        }
        protocol = 'wss' if self.ssl else 'ws'
        url = '{0}://{1}:{2}/v1/projects/{3}/subscribe?eventNames='\
            'resource.change&include=services'\
            .format(protocol, self.rancher_host, self.rancher_port,
                    self.project_id)
        self.ws = websocket.WebSocketApp(url, header=header,
                                         on_message=self._on_message,
                                         on_open=self._on_open,
                                         on_error=self._on_error,
                                         on_close=self._on_close)

        logger.info('Watching for rancher events')
        self.ws.run_forever()
项目:marconibot    作者:s4w3d0ff    | 项目源码 | 文件源码
def startWebsocket(self):
        """ Run the websocket in a thread """
        self._tick = {}
        iniTick = self.returnTicker()
        self._ids = {market: iniTick[market]['id'] for market in iniTick}
        for market in iniTick:
            self._tick[self._ids[market]] = iniTick[market]

        self._ws = WebSocketApp("wss://api2.poloniex.com/",
                                on_open=self._on_open,
                                on_message=self._on_message,
                                on_error=self._on_error,
                                on_close=self._on_close)
        self._t = _Thread(target=self._ws.run_forever)
        self._t.daemon = True
        self._t._running = True
        self._t.start()
        logger.info('Websocket thread started')
        logger.debug(self._ws.url)
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:gRPC-Makerboards    作者:PeridotYouClod    | 项目源码 | 文件源码
def serve():
  protoConfig = ProtoConfig.getConfig()
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  pushServer = Push(accessToken=protoConfig.wioLinks['havok'].accessToken)
  sensors_pb2.add_PushServicer_to_server(pushServer, server)
  port = protoConfig.ports.pushPort
  server.add_insecure_port('[::]:%s' % port)
  server.start()
  print('Started Push Server on Port %s ' % port)

  websocket.enableTrace(True)
  ws = websocket.WebSocketApp(
    "wss://us.wio.seeed.io/v1/node/event",
    on_message = pushServer.on_message,
    on_error = pushServer.on_error,
    on_close = pushServer.on_close)
  ws.on_open = pushServer.on_open
  ws.run_forever()

  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)
项目:PantherBot    作者:PantherHackers    | 项目源码 | 文件源码
def connect_to_slack(self, token):
        # Initiates connection to the server based on the token, receives websocket URL "bot_conn"
        logger.info("Starting RTM connection")
        bot_conn = self.SLACK_CLIENT.api_call(
            "rtm.start",
            token = token
        )

        logger.info("Initializing info")
        self.initialize_info()

        # Creates WebSocketApp based on the URL returned by the RTM API
        # Assigns local methods to websocket methods
        logger.info("Initializing WebSocketApplication")
        self.WEBSOCKET = websocket.WebSocketApp(bot_conn["url"],
                                on_message=self.on_message,
                                on_error=self.on_error,
                                on_close=self.on_close,
                                on_open=self.on_open)
项目:tk-photoshopcc    作者:shotgunsoftware    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:dockercloud-missing-tools    作者:apollo-13    | 项目源码 | 文件源码
def start(self):

        print ">> starting redeploy"

        self.completedHealthChecks = 0
        self.containers = []

        for container in dockercloud.Container.list(service=self.service.resource_uri):
            if container.state in ['Running', 'Starting']:
                self.containers.append(container)

        self.containers.sort(key=lambda x: x.name)

        print "found containers %s" % ', '.join([container.name for container in self.containers])

        self.websocket = websocket.WebSocketApp(
            'wss://ws.cloud.docker.com/api/audit/v1/events',
            header=['Authorization: ' + dockercloud.auth.get_auth_header()['Authorization']],
            on_message=self.onMessage,
            on_error=self.onError,
            on_open=self.onOpen
        )
        self.websocket.run_forever()
项目:siphon-cli    作者:getsiphon    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:py-pushover-open-client    作者:aeirsoul    | 项目源码 | 文件源码
def connect(self, callback, traceRoute):
        """Connects the client to the websocket"""
        if(not self.isConnected()):
            if(traceRoute):
                #Enables tracing of connection
                self.trace = True
                websocket.enableTrace(True)
            #Set callback for received messages to go to
            self.callback = callback
            #Have to put this in here, otherwise respawned dies for some reason
            self.ws = websocket.WebSocketApp(WEBSOCKET_URL,
                                on_message = self.onRecieve,
                                on_error = self.onError,
                                on_close = self.onClose)
            self.ws.on_open = self.onOpen
            #Start the actual connection
            self.mainThread = threading.Thread(target = self.ws.run_forever, args=())
            self.mainThread.start()
        else:
            print ("Attempting to connect but already connected.")
项目:peristop    作者:marin-m    | 项目源码 | 文件源码
def connect(self):
        self.ended = True
        self.hadCtrl = False
        self.reconnectTime = time()

        if self.timeout:
            self.timeout.cancel()

        ws = WebSocketApp(self.endpoint.replace('https:','wss:') + '/chatapi/v1/chatnow',
                          on_open = self.authentify,
                          on_message = self.parse,
                          on_error = self.error,
                          on_close = self.close, header={'User-Agent': 'ChatMan/1 (Android) '})

        self.timeout = Timer(80, self.ratamioche)
        self.timeout.daemon = True
        self.timeout.start()

        self.ws = ws
        ws.run_forever(sslopt=sslopt_ca_certs, ping_timeout=90)
项目:cmdchallenge-site    作者:jarv    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:bigfishtrader    作者:xingetouzi    | 项目源码 | 文件源码
def connect(self, host, apiKey, secretKey, trace=False):
        """?????"""
        self.host = host
        self.apiKey = apiKey
        self.secretKey = secretKey

        if self.host == OKCOIN_CNY:
            self.currency = CURRENCY_CNY
        else:
            self.currency = CURRENCY_USD

        websocket.enableTrace(trace)

        self.ws = websocket.WebSocketApp(host, 
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)        

        self.thread = Thread(target=self.ws.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
项目:bigfishtrader    作者:xingetouzi    | 项目源码 | 文件源码
def reconnect(self):
        """????"""
        # ?????????
        self.close()

        # ???????
        self.ws = websocket.WebSocketApp(self.host, 
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)        

        self.thread = Thread(target=self.ws.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
项目:matriz    作者:stressfm    | 项目源码 | 文件源码
def connect(self):
        time.sleep(random.randrange(0, 2**self.connection_attempts))
        self.connection_attempts += 1
        # websocket.enableTrace(True)
        ws = websocket.WebSocketApp(self.config_server_url,
                                    on_message=self.on_message,
                                    on_error=self.on_error,
                                    on_close=self.on_close)
        ws.on_open = self.on_open
        if self.config_server_url.startswith("wss://"):
            ws.run_forever(sslopt={"cert_reqs": ssl.CERT_REQUIRED,
                                   "ca_certs": ca_cert,
                                   "ssl_version": ssl.PROTOCOL_TLSv1_2,
                                   "keyfile": client_pem,
                                   "certfile": client_crt})
        else:
            ws.run_forever()
项目:matriz    作者:stressfm    | 项目源码 | 文件源码
def main():
    # websocket.enableTrace(True)
    if len(sys.argv) < 2:
        host = ws_url
    else:
        host = sys.argv[1]
    ws = websocket.WebSocketApp(host,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    if host.startswith("wss://"):
        ws.run_forever(sslopt={"cert_reqs": ssl.CERT_REQUIRED,
                               "ca_certs": ca_cert,
                               "ssl_version": ssl.PROTOCOL_TLSv1_2,
                               "keyfile": client_pem,
                               "certfile": client_crt})
    else:
        ws.run_forever()
项目:ReactiveXComponent.py    作者:xcomponent    | 项目源码 | 文件源码
def init(self, xc_api, server_url, callback):
        self.xc_api = xc_api
        self.websocket = WebSocket.WebSocketApp(server_url)

        # pylint: disable=unused-argument
        def on_message(websocket, message):
            print(message)

        def on_open(websocket):
            callback(SUCCESS, self)

        def on_error(websocket, error):
            callback(error, None)

        def on_close(websocket):
            print('### session %s closed ###' % server_url)
        # pylint: enable=unused-argument

        self.websocket.on_message = on_message
        self.websocket.on_open = on_open
        self.websocket.on_error = on_error
        self.websocket.on_close = on_close

        self.websocket.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
项目:son-cli    作者:sonata-nfv    | 项目源码 | 文件源码
def __init__(self, url, vnf_name=None, metric=None, vm_id=None,
                 desc='exported metric from SP', print=True):

        self.vnf_name = vnf_name
        self.metric = metric
        self.vc_id = vm_id #the unique identifier of the vm, used by OpenStack
        self.desc = desc
        self.print = print

        self.metric_received = False
        self.prometheus_metric = None

        websocket.WebSocketApp.__init__(self, url,
                                        on_message=self._on_message,
                                        on_error=self._on_error,
                                        on_close=self._on_close,
                                        on_open=self._on_open
                                        )
项目:Flask-SocketIO    作者:cutedogspark    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:mist.api    作者:mistio    | 项目源码 | 文件源码
def command(self, cmd):
        self.cmd = self._wrap_command(cmd)
        log.error(self.cmd)

        self.ws = websocket.WebSocketApp(self.uri,
                                         on_message=self._on_message,
                                         on_error=self._on_error,
                                         on_close=self._on_close)

        log.error(self.ws)
        self.ws.on_open = self._on_open
        self.ws.run_forever(ping_interval=3, ping_timeout=10)
        self.ws.close()
        retval = 0
        output = self.buffer.split("\n")[1:-1]
        return retval, "\n".join(output)
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def __init__(self, board_id, access_token, user_id):
        self.board_id = board_id
        self.access_token = access_token
        self.user_id = user_id
        self.turn = None
        self.v_board = ReversiBoard()
        ws = websocket.WebSocketApp(
            f"ws://localhost:8000/v1/board/{self.board_id}/ws",
            header=[f"Authorization: Bearer {self.access_token}"],
            on_open=self.on_open,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close,
        )
        try:
            ws.run_forever()
        except KeyboardInterrupt:
            ws.close()
项目:smileybot    作者:sillylyn    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:octoclient    作者:hroncok    | 项目源码 | 文件源码
def run(self):
        """
        Runs thread, which listens on socket.
        Executes given callbacks on events
        """
        def on_message(ws, data):
            if data.startswith('m'):
                self.on_message(ws, json.loads(data[1:]))
            elif data.startswith('a'):
                for msg in json.loads(data[1:]):
                    self.on_message(ws, msg)

        self.socket = websocket.WebSocketApp(self.url,
                                             on_open=self.on_open,
                                             on_close=self.on_close,
                                             on_message=on_message)
        self.thread = Thread(target=self.socket.run_forever)
        self.thread.daemon = True
        self.thread.start()
项目:bonsai-cli    作者:BonsaiAI    | 项目源码 | 文件源码
def run(self):
        ws = websocket.WebSocketApp(
            self._ws_url,
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=LogStreamHandler.on_close,
            header=['Authorization: {}'.format(self._access_key)]
        )
        ws.on_open = self._on_open
        log.debug("Starting websocket connection for bonsai log --follow...")

        proxy = self._get_proxy()
        log.debug('proxy: %s', proxy)

        try:
            ws.run_forever(**proxy)
        except KeyboardInterrupt as e:
            log.debug("Handling user Ctrl+C")
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:deb-python-websocket-client    作者:openstack    | 项目源码 | 文件源码
def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
项目:IotCenter    作者:panjanek    | 项目源码 | 文件源码
def start(self):
        self.windowThread = threading.Thread(target = self.window.start)
        self.windowThread.daemon = True
        self.windowThread.start() 
        while True:
            try:
                self.ws = websocket.WebSocketApp(self.apiAddr,on_message = self.on_message,on_error = self.on_error,on_close = self.on_close)
                self.ws.on_open = self.on_open
                self.ws.run_forever()
            except:
                self.logger.error("websocket connection error, reconnecting...")
            time.sleep(10)
项目:bearychat.py    作者:bearyinnovative    | 项目源码 | 文件源码
def __init__(self, ws_host):
        self._call_id = 0
        self._inbox = Queue()
        self._errors = Queue()
        self._ws = websocket.WebSocketApp(
            ws_host,
            on_open=self.on_open,
            on_message=self.on_message,
            on_close=self.on_close,
            on_error=self.on_error)
        self._worker = threading.Thread(
            target=self._ws.run_forever,
            kwargs={'sslopt': sslopt_with_ca_certs})
项目:AlexaPi    作者:alexa-pi    | 项目源码 | 文件源码
def init_connection(self):
        logger.debug('Initializing connection')
        if self._pconfig['verbose']:
            websocket.enableTrace(True)
        self.socket = websocket.WebSocketApp(self.service,
                on_message=self.on_socket_message,
                on_close=self.on_socket_close,
                on_error=self.on_socket_error)
        self.socket_thread = threading.Thread(target=self.socket.run_forever)
        self.socket_thread.daemon = True
        self.socket_thread.start()
项目:sensorbee-python    作者:kmaehashi    | 项目源码 | 文件源码
def setup(self, **kwargs):
        """
        ``setup`` is a low-level interface for users who need to configure
        WebSocketApp details.
        """
        self._app = websocket.WebSocketApp(
            self._uri,
            on_open=self._on_open,
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close,
            **kwargs
        )
项目:slack-bomber    作者:setokinto    | 项目源码 | 文件源码
def connect():
    global connected
    if connected:
        return
    connected = True
    slacker = Slacker(API_TOKEN)
    url = slacker.rtm.start().body["url"]
    ws = WebSocketApp(url,
                      on_message = on_message,
                      on_error = on_error,
                      on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testKeepRunning(self):
        """ A WebSocketApp should keep running as long as its self.keep_running
        is not False (in the boolean context).
        """

        def on_open(self, *args, **kwargs):
            """ Set the keep_running flag for later inspection and immediately
            close the connection.
            """
            WebSocketAppTest.keep_running_open = self.keep_running

            self.close()

        def on_close(self, *args, **kwargs):
            """ Set the keep_running flag for the test to use.
            """
            WebSocketAppTest.keep_running_close = self.keep_running

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, on_close=on_close)
        app.run_forever()

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_open,
                                    WebSocketAppTest.NotSetYet))

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_close,
                                    WebSocketAppTest.NotSetYet))

        self.assertEqual(True, WebSocketAppTest.keep_running_open)
        self.assertEqual(False, WebSocketAppTest.keep_running_close)
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testKeepRunning(self):
        """ A WebSocketApp should keep running as long as its self.keep_running
        is not False (in the boolean context).
        """

        def on_open(self, *args, **kwargs):
            """ Set the keep_running flag for later inspection and immediately
            close the connection.
            """
            WebSocketAppTest.keep_running_open = self.keep_running

            self.close()

        def on_close(self, *args, **kwargs):
            """ Set the keep_running flag for the test to use.
            """
            WebSocketAppTest.keep_running_close = self.keep_running

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, on_close=on_close)
        app.run_forever()

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_open,
                                    WebSocketAppTest.NotSetYet))

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_close,
                                    WebSocketAppTest.NotSetYet))

        self.assertEqual(True, WebSocketAppTest.keep_running_open)
        self.assertEqual(False, WebSocketAppTest.keep_running_close)
项目:BitcoinExchangeFH    作者:Aurora-Team    | 项目源码 | 文件源码
def connect(self, url,
                on_message_handler=None,
                on_open_handler=None,
                on_close_handler=None,
                on_error_handler=None,
                reconnect_interval=10):
        """
        :param url: Url link
        :param on_message_handler: Message handler which take the message as
                           the first argument
        :param on_open_handler: Socket open handler which take the socket as
                           the first argument
        :param on_close_handler: Socket close handler which take the socket as
                           the first argument
        :param on_error_handler: Socket error handler which take the socket as
                           the first argument and the error as the second
                           argument
        :param reconnect_interval: The time interval for reconnection
        """
        Logger.info(self.__class__.__name__, "Connecting to socket <%s>..." % self.id)
        if on_message_handler is not None:
            self.on_message_handlers.append(on_message_handler)
        if on_open_handler is not None:
            self.on_open_handlers.append(on_open_handler)
        if on_close_handler is not None:
            self.on_close_handlers.append(on_close_handler)
        if on_error_handler is not None:
            self.on_error_handlers.append(on_error_handler)

        if not self._connecting and not self._connected:
            self._connecting = True
            self.ws = websocket.WebSocketApp(url,
                                             on_message=self.__on_message,
                                             on_close=self.__on_close,
                                             on_open=self.__on_open,
                                             on_error=self.__on_error)
            self.wst = threading.Thread(target=lambda: self.__start(reconnect_interval=reconnect_interval))
            self.wst.start()

        return self.wst
项目:twitch-bits-info    作者:floweb    | 项目源码 | 文件源码
def start(self):
        # Standard REST API:
        # This is use to get channel_id from a channel_name,
        # and the OAuth token needed for Websocket requests
        self.twitch = pytwitcherapi.TwitchSession()

        self.twitch_login()
        self.access_token = self.twitch.token['access_token']
        try:
            self.channel_id
        except AttributeError:
            self.channel_id = self.get_channel_id()
            self._write_config('channel_id', self.channel_id)

        if self.first_run:
            # First run was a success, we don't need to wait 45 seconds for user login
            # Set first_run param to 0 (== False)
            self._write_config('first_run', '0')

        # Websocket / PubSub:
        # This is use to get Twitch's Bits information stream
        if self.verbose:
            websocket.enableTrace(True)

        self.twitch.ws = websocket.WebSocketApp(
            self.ws_host,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=lambda _: self.log.info("Terminating...")
        )

        self.cm = ConsoleMini(db_filepath=self.db_filepath, log=self.log)

        self.twitch.ws.on_open = self.on_open
        self.twitch.ws.run_forever()
项目:pynextion    作者:raffmont    | 项目源码 | 文件源码
def run(self):
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp(self.url,
                                on_message = self.on_message,
                                on_error = self.on_error,
                                on_close = self.on_close)
        ws.on_open = self.on_open
        ws.run_forever()
项目:bitmex-websocket    作者:joliveros    | 项目源码 | 文件源码
def init_websocket(self):
        wsURL = self.build_websocket_url()
        alog.debug("Connecting to %s" % (wsURL))
        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth(),
                                         on_ping=self.__on_ping,
                                         on_pong=self.__on_pong)
项目:python-muse    作者:aaroncox    | 项目源码 | 文件源码
def run_forever(self):
        """ This method is used to run the websocket app continuously.
            It will execute callbacks as defined and try to stay
            connected with the provided APIs
        """
        cnt = 0
        while True:
            cnt += 1
            self.url = next(self.urls)
            log.debug("Trying to connect to node %s" % self.url)
            try:
                # websocket.enableTrace(True)
                self.ws = websocket.WebSocketApp(
                    self.url,
                    on_message=self.on_message,
                    # on_data=self.on_message,
                    on_error=self.on_error,
                    on_close=self.on_close,
                    on_open=self.on_open
                )
                self.ws.run_forever()
            except websocket.WebSocketException as exc:
                if (self.num_retries >= 0 and cnt > self.num_retries):
                    raise NumRetriesReached()

                sleeptime = (cnt - 1) * 2 if cnt < 10 else 10
                if sleeptime:
                    log.warning(
                        "Lost connection to node during wsconnect(): %s (%d/%d) "
                        % (self.url, cnt, self.num_retries) +
                        "Retrying in %d seconds" % sleeptime
                    )
                    time.sleep(sleeptime)

            except KeyboardInterrupt:
                self.ws.keep_running = False
                raise

            except Exception as e:
                log.critical("{}\n\n{}".format(str(e), traceback.format_exc()))
项目:tk-photoshopcc    作者:shotgunsoftware    | 项目源码 | 文件源码
def testKeepRunning(self):
        """ A WebSocketApp should keep running as long as its self.keep_running
        is not False (in the boolean context).
        """

        def on_open(self, *args, **kwargs):
            """ Set the keep_running flag for later inspection and immediately
            close the connection.
            """
            WebSocketAppTest.keep_running_open = self.keep_running

            self.close()

        def on_close(self, *args, **kwargs):
            """ Set the keep_running flag for the test to use.
            """
            WebSocketAppTest.keep_running_close = self.keep_running

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, on_close=on_close)
        app.run_forever()

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_open,
                                    WebSocketAppTest.NotSetYet))

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_close,
                                    WebSocketAppTest.NotSetYet))

        self.assertEqual(True, WebSocketAppTest.keep_running_open)
        self.assertEqual(False, WebSocketAppTest.keep_running_close)
项目:cli    作者:riseml    | 项目源码 | 文件源码
def stream(self):
        ws_app = websocket.WebSocketApp(
            self.url,
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close
        )
        # FIXME: {'Authorization': os.environ.get('RISEML_APIKEY')}
        ws_app.run_forever()
项目:mopidy-json-client    作者:ismailof    | 项目源码 | 文件源码
def _ws_connect(self):
        # Initialize websocket parameters
        self.wsa = websocket.WebSocketApp(
            url=self.ws_url,
            on_message=self._server_response,
            on_error=self._ws_error,
            on_open=self._ws_open,
            on_close=self._ws_close)

        # Run the websocket in parallel thread
        self.wsa_thread = threading.Thread(
            target=self.wsa.run_forever,
            name='WSA-Thread')
        self.wsa_thread.setDaemon(True)
        self.wsa_thread.start()
项目:wpiao    作者:chuqingq    | 项目源码 | 文件源码
def start_websocket():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://192.168.31.71:8080/api/ws/runner",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

# print('start_websocket...')
# t = threading.Thread(target=start_websocket, args=())
# t.start()
项目:OctoPrint-Dashboard    作者:meadowfrey    | 项目源码 | 文件源码
def run_with_id(self, printer_id):
        """
        Runs thread, which listens on socket.
        Executes given callbacks on events
        """

        def on_message(ws, data):
            if data.startswith('m'):
                self.on_message(ws, json.loads(data[1:]))
            elif data.startswith('a'):
                for msg in json.loads(data[1:]):
                    self.on_message(ws, msg, printer_id)

        def on_error(ws, exception):
            data = {
                "id": printer_id,
                "state": {
                    "text": "Offline/Unreachable"
                }
            }
            socketio.emit("status", data, room=str(printer_id))

        self.socket = websocket.WebSocketApp(self.url,
                                             on_open=self.on_open,
                                             on_close=self.on_close,
                                             on_message=on_message,
                                             on_error=on_error)
        self.thread = Thread(target=self.run_forever)
        self.thread.daemon = True
        self.thread.start()