我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用websocket.enableTrace()。
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)
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.")
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() #----------------------------------------------------------------------
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()
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()
def websocket_debug(): websocket.enableTrace(True)
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()
def setUp(self): ws.enableTrace(TRACABLE)
def setUp(self): ws.enableTrace(TRACABLE) WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
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()
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()
def connect(self): """ Initialize a websocket handshake. """ tc_header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Sec-WebSocket-Protocol': 'tc', 'Sec-WebSocket-Extensions': 'permessage-deflate' } # Comment out next 2 lines to not # have debug info from websocket show in console. if config.DEBUG_MODE: websocket.enableTrace(True) self._ws = websocket.create_connection( 'wss://wss.tinychat.com', header=tc_header, origin='https://tinychat.com' ) if self._ws.connected: log.info('connecting to: %s' % self.room_name) if self.send_join_msg(): self.is_connected = True self.__callback()
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()))
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()
def main(): # Connect to websocket interfaces headers = {} userpass = ":".join(get_auth()) headers["Authorization"] = "Basic " + base64.b64encode( userpass.encode()).decode() url = ("wss://stream.watsonplatform.net//speech-to-text/api/v1/recognize" "?model=en-US_BroadbandModel") # 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()
def setUp(self): ws.enableTrace(TRACEABLE)
def setUp(self): ws.enableTrace(TRACEABLE) WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
def __init__(self, url, token, on_message): #websocket.enableTrace(True) self.ws = websocket.WebSocketApp(url, on_message = on_message, on_error = self.on_error, on_close = self.on_close, header = ["Authorization: Bearer " + token], subprotocols=["binary", "base64"])
def run_client(host_url): websocket.enableTrace(True) ws = websocket.WebSocketApp(host_url, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() # run_client('ws://192.168.43.114:8000/bot')
def connect(self): screepsConnection = API(u=self.user,p=self.password,ptr=self.ptr,host=self.host,secure=self.secure) me = screepsConnection.me() self.user_id = me['_id'] self.token = screepsConnection.token if self.logging: logging.getLogger('websocket').addHandler(logging.StreamHandler()) websocket.enableTrace(True) else: logging.getLogger('websocket').addHandler(logging.NullHandler()) websocket.enableTrace(False) if self.host: url = 'wss://' if self.secure else 'ws://' url += self.host + '/socket/websocket' elif not self.ptr: url = 'wss://screeps.com/socket/websocket' else: url = 'wss://screeps.com/ptr/socket/websocket' self.ws = websocket.WebSocketApp(url=url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open) ssl_defaults = ssl.get_default_verify_paths() sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile} if 'http_proxy' in self.settings and self.settings['http_proxy'] is not None: http_proxy_port = self.settings['http_proxy_port'] if 'http_proxy_port' in self.settings else 8080 self.ws.run_forever(http_proxy_host=self.settings['http_proxy'], http_proxy_port=http_proxy_port, ping_interval=1, sslopt=sslopt_ca_certs) else: self.ws.run_forever(ping_interval=1, sslopt=sslopt_ca_certs)
def __init__(self, ip, password): ConBase.__init__(self) threading.Thread.__init__(self) self.daemon = True self.fifo = deque() self.fifo_lock = threading.Lock() # websocket.enableTrace(logging.root.getEffectiveLevel() < logging.INFO) self.ws = websocket.WebSocketApp("ws://%s:8266" % ip, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close) self.start() self.timeout = 5.0 if b'Password:' in self.read(256, blocking=False): self.ws.send(password + "\r") if not b'WebREPL connected' in self.read(256, blocking=False): raise ConError() else: raise ConError() self.timeout = 1.0 logging.info("websocket connected to ws://%s:8266" % ip)
def run(params): signal.signal(signal.SIGINT, signal_handler) #Assign the signal handler if(sdnpwn.checkArg(["-t", "--target"], params)): port = str(sdnpwn.getArg(["-p", "--port"], params, 8181)) cookie = sdnpwn.getArg(["-c", "--cookie"], params, None) wsURL = "ws://" + sdnpwn.getArg(["-t", "--target"], params) + ":" + port + "/onos/ui/websock/core" #websocket.enableTrace(True) ws = websocket.WebSocketApp(wsURL) ws.on_open = onOpen ws.on_message = onMessage ws.on_error = onError ws.on_close = onClose ws.sdnpwn_params = params ws.sdnpwn_expected_events = 1 #Execting initial bootstrap event if(cookie is not None): ws.cookie = cookie sdnpwn.printNormal("Attempting connection to " + wsURL) ws.run_forever() else: print(usage())
def __init__( self, key=None, ws_url='wss://metasmoke.erwaysoftware.com/cable', enable_trace=False): self.key = key if enable_trace: websocket.enableTrace(True) self.ws = websocket.WebSocketApp( ws_url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close) self.ws.on_open = self.on_open self.type_hooks = { 'ping': self.on_ping, 'welcome': self.on_welcome, 'confirm_subscription': self.on_subscription_confirmed } self.message_hooks = { 'flag_log': self.on_flag, 'feedback': self.on_feedback, 'deletion_log': self.on_delete, 'not_flagged': self.on_not_flagged, 'statistic': self.on_statistic } self.last_ping_time = None self.sub_id = None # Make it easy for subclasses self.init_hook() self.ws.run_forever()
def run(self): websocket.enableTrace(False) ws = websocket.WebSocketApp(self.wsUrl, on_message = self.websocketMessage, on_error = self.websocketError, on_close = self.websocketClose, on_open = self.subscribePublicChannels) ws.run_forever()