Python websocket.WebSocketApp() Examples
The following are 30
code examples of websocket.WebSocketApp().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
websocket
, or try the search function
.
Example #1
Source File: ws_client.py From plugin.video.emby with GNU General Public License v3.0 | 9 votes |
def run(self): token = self.client['config/auth.token'] device_id = self.client['config/app.device_id'] server = self.client['config/auth.server'] server = server.replace('https', "wss") if server.startswith('https') else server.replace('http', "ws") wsc_url = "%s/embywebsocket?api_key=%s&device_id=%s" % (server, token, device_id) LOG.info("Websocket url: %s", wsc_url) self.wsc = websocket.WebSocketApp(wsc_url, on_message=self.on_message, on_error=self.on_error) self.wsc.on_open = self.on_open while not self.stop: self.wsc.run_forever(ping_interval=10) if self.stop: break time.sleep(5) self.client['callback_ws']('WebSocketRestarting') LOG.info("---<[ websocket ]")
Example #2
Source File: proxy.py From Cloudroid with BSD 3-Clause "New" or "Revised" License | 7 votes |
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))
Example #3
Source File: vnokex.py From vnpy_crypto with MIT License | 7 votes |
def connect(self, apiKey, secretKey, trace=False): self.host = OKEX_USD_CONTRACT self.apiKey = apiKey self.secretKey = secretKey self.trace = trace websocket.enableTrace(trace) 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, args=(None, None, 60, 30)) self.thread.start() # ----------------------------------------------------------------------
Example #4
Source File: vngateio_ws.py From vnpy_crypto with MIT License | 7 votes |
def connect_Subpot(self, apiKey , secretKey , trace = False): self.host = GATEIO_SOCKET_URL self.apiKey = apiKey self.secretKey = secretKey self.trace = trace websocket.enableTrace(trace) 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 , args = (None , None , 60, 30)) # self.thread_heart = Thread(target = self.run_forever_heart) self.thread.start() # self.thread_heart.start() #----------------------------------------------------------------------
Example #5
Source File: test_websocket.py From vnpy_crypto with MIT License | 7 votes |
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() # if numpu is installed, this assertion fail # 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))
Example #6
Source File: vngateio_ws.py From vnpy_crypto with MIT License | 7 votes |
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 , args = (None , None , 60, 30)) self.thread.start() #----------------------------------------------------------------------
Example #7
Source File: __init__.py From marconibot with GNU General Public License v3.0 | 6 votes |
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)
Example #8
Source File: vnfcoin.py From vnpy_crypto with MIT License | 6 votes |
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 , args = (None , None , 60, 30)) self.thread.start() #----------------------------------------------------------------------
Example #9
Source File: __init__.py From slouch with MIT License | 6 votes |
def run_forever(self): """Run the bot, blocking forever.""" res = self.slack.rtm.start() self.log.info("current channels: %s", ','.join(c['name'] for c in res.body['channels'] if c['is_member'])) self.id = res.body['self']['id'] self.name = res.body['self']['name'] self.my_mention = "<@%s>" % self.id self.ws = websocket.WebSocketApp( res.body['url'], on_message=self._on_message, on_error=self._on_error, on_close=self._on_close, on_open=self._on_open) self.prepare_connection(self.config) self.ws.run_forever()
Example #10
Source File: WebSocketClient.py From vnpy_crypto with MIT License | 6 votes |
def _connect(self): self._log.debug('初始化websocket并发起链接') self._socket = websocket.WebSocketApp( self._url, on_open=self._on_open, on_message=self._on_message, on_close=self._on_close, on_error=self._on_error ) self._socket.run_forever() # 以下用于重连 while self._reconnect_required.is_set(): if not self._disconnecte_required.is_set(): self._socket.sock = None delay = self._reconnect_interval while delay > 0: self._log.info('%ds 后重连' % delay) time.sleep(1) delay -= 1 self._socket.keep_running = True self._socket.run_forever()
Example #11
Source File: test_sonoff.py From sonoff-lan-mode-homeassistant with MIT License | 6 votes |
def __init__(self, sonoff, on_message=None, on_error=None): self.logger = sonoff.logger self._sonoff = sonoff websocket_host = 'ws://{}:{}{}'.format(self._sonoff.get_wshost(), self._sonoff.get_wsport(), self._sonoff.get_wsendpoint()) self.logger.info('WebsocketListener initialising, connecting to host: %s' % websocket_host) threading.Thread.__init__(self) websocket.WebSocketApp.__init__(self, websocket_host, on_open=self.on_open, on_error=on_error, on_message=on_message, on_close=self.on_close) self.connected = False self.last_update = time.time()
Example #12
Source File: bitmex_websocket.py From archon with MIT License | 6 votes |
def __connect(self, wsURL, symbol): '''Connect to the websocket in a thread.''' self.logger.debug("Starting thread") 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()) self.wst = threading.Thread(target=lambda: self.ws.run_forever()) self.wst.daemon = True self.wst.start() self.logger.debug("Started thread") # Wait for connect before continuing conn_timeout = 5 while not self.ws.sock or not self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout -= 1 if not conn_timeout: self.logger.error("Couldn't connect to WS! Exiting.") self.exit() raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.')
Example #13
Source File: deribit_ws.py From archon with MIT License | 6 votes |
def connect(self): self.logger.info("connect ws") websocket.enableTrace(True) self.ws = websocket.WebSocketApp("wss://www.deribit.com/ws/api/v1/", on_message = lambda ws,msg: self.on_message(ws, msg), on_error = lambda ws,msg: self.on_error(ws, msg), on_open = lambda ws: self.on_open(ws), #on_open = self.on_open, on_close = self.on_close) ssl_defaults = ssl.get_default_verify_paths() sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile} self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt=sslopt_ca_certs)) self.wst.daemon = True self.wst.start() self.logger.info("Started thread") #TOOD subscribe later #self.ws.run_forever()
Example #14
Source File: transcribe.py From watson-streaming-stt with Apache License 2.0 | 6 votes |
def main(): # Connect to websocket interfaces headers = {} userpass = ":".join(get_auth()) headers["Authorization"] = "Basic " + base64.b64encode( userpass.encode()).decode() url = get_url() # If you really want to see everything going across the wire, # uncomment this. However realize the trace is going to also do # things like dump the binary sound packets in text in the # console. # # websocket.enableTrace(True) ws = websocket.WebSocketApp(url, header=headers, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.args = parse_args() # This gives control over the WebSocketApp. This is a blocking # call, so it won't return until the ws.close() gets called (after # 6 seconds in the dedicated thread). ws.run_forever()
Example #15
Source File: vnfcoin.py From vnpy_crypto with MIT License | 6 votes |
def connect_Subpot(self , trace = False): self.host = FCOIN_WSS_HOST self.trace = trace websocket.enableTrace(trace) 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 , args = (None , None , 60, 30)) # self.thread_heart = Thread(target = self.run_forever_heart) self.thread.start() # self.thread_heart.start() #----------------------------------------------------------------------
Example #16
Source File: vnokcoin.py From chanlun with MIT License | 6 votes |
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() #----------------------------------------------------------------------
Example #17
Source File: vnokcoin.py From chanlun with MIT License | 6 votes |
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() #----------------------------------------------------------------------
Example #18
Source File: nicolive.py From streamlink with BSD 2-Clause "Simplified" License | 6 votes |
def api_connect(self, url): # Proxy support adapted from the UStreamTV plugin (ustreamtv.py) proxy_url = self.session.get_option("https-proxy") if proxy_url is None: proxy_url = self.session.get_option("http-proxy") proxy_options = parse_proxy_url(proxy_url) if proxy_options.get('http_proxy_host'): _log.debug("Using proxy ({0}://{1}:{2})".format( proxy_options.get('proxy_type') or "http", proxy_options.get('http_proxy_host'), proxy_options.get('http_proxy_port') or 80)) _log.debug("Connecting: {0}".format(url)) self._ws = websocket.WebSocketApp( url, header=["User-Agent: {0}".format(useragents.CHROME)], on_open=self.api_on_open, on_message=self.handle_api_message, on_error=self.api_on_error) self.ws_worker_thread = threading.Thread( target=self._ws.run_forever, args=proxy_options) self.ws_worker_thread.daemon = True self.ws_worker_thread.start()
Example #19
Source File: pushbullet.py From xbmc.service.pushbullet with GNU General Public License v3.0 | 6 votes |
def _websocketThread(self, evtThreadEnded): try: websocket.enableTrace(False) self._ws = websocket.WebSocketApp(self._REST_URLS['websocket'] + self.access_token, on_open=self._on_open, on_message=self._on_message, on_close=self._on_close, on_error=self._on_error) # ping_timeout is for no blocking call self._ws.run_forever(ping_interval=self.ping_timeout/2, ping_timeout=self.ping_timeout) except AttributeError: self._on_error(websocket, 'No internet connection!') except Exception as ex: self._on_error(websocket, ex) finally: evtThreadEnded.set()
Example #20
Source File: websocket_manage.py From huobi_Python with Apache License 2.0 | 6 votes |
def websocket_func(*args): try: websocket_manage = args[0] websocket_manage.original_connection = websocket.WebSocketApp(websocket_manage.url, on_message=on_message, on_error=on_error, on_close=on_close) global websocket_connection_handler websocket_connection_handler[websocket_manage.original_connection] = websocket_manage websocket_manage.logger.info("[Sub][" + str(websocket_manage.id) + "] Connecting...") websocket_manage.original_connection.on_open = on_open websocket_manage.original_connection.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) websocket_manage.logger.info("[Sub][" + str(websocket_manage.id) + "] Connection event loop down") if websocket_manage.state == ConnectionState.CONNECTED: websocket_manage.state = ConnectionState.IDLE except Exception as ex: print(ex)
Example #21
Source File: test_websocket.py From deepWordBug with Apache License 2.0 | 6 votes |
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() # if numpu is installed, this assertion fail # 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))
Example #22
Source File: QAhuobi_realtime.py From QUANTAXIS with MIT License | 6 votes |
def run_subscription_batch_jobs(self): """ 请求 KLine 实时数据 """ websocket.enableTrace(False) self.__ws = websocket.WebSocketApp( self.HUOBIPRO_WEBSOCKET_URL, on_message=self.on_message, on_open=self.on_open, on_error=self.on_error, on_close=self.on_close ) self.__locked = True # 如果意外退出,等待10秒重新运行 while (True): self.__ws.run_forever() QA_util_log_expection("FTW! it quit! Retry 10 seconds later...") time.sleep(10)
Example #23
Source File: proxy.py From Cloudroid with BSD 3-Clause "New" or "Revised" License | 6 votes |
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))
Example #24
Source File: proxy.py From Cloudroid with BSD 3-Clause "New" or "Revised" License | 6 votes |
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))
Example #25
Source File: bitmex_websocket.py From ebisu with MIT License | 6 votes |
def __on_close(self, ws): """ On Close Listener :param ws: """ if 'close' in self.handlers: self.handlers['close']() if self.is_running: logger.info("Websocket restart") notify(f"Websocket restart") self.ws = websocket.WebSocketApp(self.endpoint, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close, header=self.__get_auth()) self.wst = threading.Thread(target=self.__start) self.wst.daemon = True self.wst.start()
Example #26
Source File: bitmex_websocket.py From ebisu with MIT License | 6 votes |
def __init__(self, test=False): """ constructor """ self.testnet = test if test: domain = 'testnet.bitmex.com' else: domain = 'www.bitmex.com' self.endpoint = 'wss://' + domain + '/realtime?subscribe=tradeBin1m:XBTUSD,' \ 'tradeBin5m:XBTUSD,tradeBin1h:XBTUSD,tradeBin1d:XBTUSD,instrument:XBTUSD,' \ 'margin,position:XBTUSD,wallet,orderBookL2:XBTUSD' self.ws = websocket.WebSocketApp(self.endpoint, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close, header=self.__get_auth()) self.wst = threading.Thread(target=self.__start) self.wst.daemon = True self.wst.start()
Example #27
Source File: client.py From ParlAI with MIT License | 6 votes |
def _run(ws, id): """ Takes user input and sends it to a websocket. :param ws: websocket.WebSocketApp """ while True: x = input("\033[44m Me: ") print("\033[0m", end="") data = {} data['id'] = id data['text'] = x json_data = json.dumps(data) ws.send(json_data) time.sleep(1) if x == "[DONE]": break ws.close()
Example #28
Source File: connection.py From Pysher with MIT License | 6 votes |
def _connect(self): self.state = "connecting" self.socket = websocket.WebSocketApp( self.url, on_open=self._on_open, on_message=self._on_message, on_error=self._on_error, on_close=self._on_close ) self.socket.run_forever(**self.socket_kwargs) while self.needs_reconnect and not self.disconnect_called: self.logger.info("Attempting to connect again in %s seconds." % self.reconnect_interval) self.state = "unavailable" time.sleep(self.reconnect_interval) # We need to set this flag since closing the socket will set it to # false self.socket.keep_running = True self.socket.run_forever(**self.socket_kwargs)
Example #29
Source File: __init__.py From slouch with MIT License | 5 votes |
def __init__(self, slack_token, config): """ Do not override this to perform implementation-specific setup; use :func:`prepare_bot` instead. No IO will be done until :func:`run_forever` is called (unless :func:`prepare_bot` is overridden to perform some). :param slack_token: a Slack api token. :param config: an arbitrary dictionary for implementation-specific configuration. The same object is stored as the `config` attribute and passed to prepare methods. """ #: the same config dictionary passed to init. self.config = config self._current_message_id = 0 #: a Logger (``logging.getLogger(__name__)``). self.log = logging.getLogger(__name__) # This doesn't perform IO. #: a `Slacker <https://github.com/os/slacker>`__ instance created with `slack_token`. self.slack = Slacker(slack_token) #: the bot's Slack id. #: Not available until :func:`prepare_connection`. self.id = None #: the bot's Slack name. #: Not available until :func:`prepare_connection`. self.name = None #: the bot's Slack mention, equal to ``<@%s> % self.id`` . #: Not available until :func:`prepare_connection`. self.my_mention = None #: a `WebSocketApp <https://github.com/liris/websocket-client>`__ instance. #: Not available until :func:`prepare_connection`. self.ws = None self.prepare_bot(self.config)
Example #30
Source File: trello.py From platypush with MIT License | 5 votes |
def _send(self, ws: WebSocketApp, msg: dict): msg['reqid'] = self._req_id ws.send(json.dumps(msg)) self._req_id += 1