我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用websocket.create_connection()。
def stream_output(gpu_ip, ws_port, job_hash): # connect to the websocket for this job url = 'ws://%s:%s' % (gpu_ip, ws_port) ws = create_connection(url) # send over the job hash to start the job ws.send(job_hash) # print all the outputs of the script to the screen # try: while True: msg = ws.recv() msgJson = json.loads(msg) if 'end' in msgJson: break else: print(msgJson['message'], end='') ws.close() return msgJson['hasResult'] # if the user interrupts the job, decide whether or not to stop # except KeyboardInterrupt: # # propagate the exception for the layer above to handle # raise JobInterruptedException()
def _connect_and_join(self, userid, username, mode, gameid, force_start, public_server): logging.debug("Creating connection") self._ws = create_connection(ENDPOINT_BOT if not public_server else ENDPOINT_PUBLIC) self._lock = threading.RLock() _spawn(self._start_sending_heartbeat) self._send(["set_username", userid, username, BOT_KEY]) logging.info("Joining game") self._gameid = None if mode == "private": self._gameid = gameid if gameid is None: raise ValueError("Gameid must be provided for private games") self._send(["join_private", gameid, userid, BOT_KEY]) elif mode == "1v1": self._send(["join_1v1", userid, BOT_KEY]) elif mode == "team": self._send(["join_team", userid, BOT_KEY]) elif mode == "ffa": self._send(["play", userid, BOT_KEY]) else: raise ValueError("Invalid mode") if force_start: _spawn(self.send_forcestart)
def connect(self): """ Opens a connection """ ws = None # Let us discover, where we need to connect to if self.ip == None or self.port == None: (ws, self.usn, self.apiV, self.srv) = ssdp.discover(None) else: ws = "ws://%s" % self.ip if not self.port is None: ws = "{}:{}".format(ws, self.port) if not self.path is None: ws = "{}/{}".format(ws, self.path) if ws == None: return False self.ws = websocket.create_connection(ws) return True
def _data_thread(self): try: conn = create_connection(self.addr) except Exception: self._controller_q.put('restart_data') return while self.running: try: data = conn.recv() data = json.loads(data) except WebSocketTimeoutException: self._controller_q.put('restart_data') return try: pair = data['MarketDataIncrementalRefresh']['symbol'] endpoint = 'MarketDataIncrementalRefresh' except KeyError: pair = data['MarketDataSnapshotFullRefresh']['symbol'] endpoint = 'MarketDataSnapshotFullRefresh' self.data_q.put((endpoint, pair, data[endpoint], time.time()))
def start_websocket(self): logging.info("Connecting to MOD-UI websocket...") i=0 while i<100: try: self.websocket = websocket.create_connection(self.websocket_url) break except: i=i+1 sleep(0.1) if i<100: self.ws_thread=Thread(target=self.task_websocket, args=()) self.ws_thread.daemon = True # thread dies with the program self.ws_thread.start() return True else: return False
def stream_logs(): conf = Config() # Request the correct streamer URL from siphon-web auth = Auth() siphon = Siphon(auth.auth_token) # Track mixpanel_event(MIXPANEL_EVENT_LOGS, properties={'app_id': conf.app_id}) streamer_url = siphon.get_streamer_url(conf.app_id, 'log_reader') puts(colored.yellow('Connecting...')) ws = websocket.create_connection(streamer_url) puts(colored.green('Streaming logs and errors... (ctrl-c to stop)\n')) try: for line in ws: print(line) except KeyboardInterrupt: puts(colored.yellow('\nClosing the connection.')) ws.close()
def check_ws_api(): """Check websocket API.""" success = True try: for api in context.GLOBAL.ws_api(None): try: ws_client.create_connection(api) _LOGGER.debug('%s - ok.', api) except socket.error: _LOGGER.error('%s - failed.', api) success = False except context.ContextError as err: _LOGGER.error('Unable to resolve websocket api: %r', str(err)) success = False return success
def connect_socket(url, timeout=TIMEOUT, **kwargs): """set up a websocket and return the socket connection object""" signal.signal( signal.SIGALRM, lambda s, f: timeout_handler(s, f, f'connecting ({timeout}s)') ) signal.alarm(timeout) try: sock = create_connection(url, **kwargs) signal.alarm(0) return sock except Exception: signal.alarm(0) print(f'[X] Failed to connect, is runserver running on {url}?') raise except Exception: signal.alarm(0) raise
def run(self): signal.alarm(0) self.ws = create_connection(self.url, **self.socket_options) self.ws.send(json.dumps(self.get_message())) resp = self.ws.recv() resp = self.ws.recv() assert resp and self.check_response(json.loads(resp)), \ 'Failed to get expected response from backend.' self.started.set() self.should_start.wait() while self.keep_running: try: msg = self.get_message() self.ws.send(json.dumps(msg)) resp = json.loads(self.ws.recv()) if self.verbose: print('sent:', msg[ROUTING_KEY], ' recv:', resp[ROUTING_KEY]) assert resp and self.check_response(resp), \ 'Failed to get expected response from backend.' self.round_trips += 1 except Exception: if self.keep_running: raise
def __init__(self, host, port, tabs=None, tab_id=None): super().__init__(host, port) self._host = host self._port = port if tab_id is None: tab_info = json.loads(call_method(self._host, self._port, 'new')) self._id = tab_info['id'] self._ws_url = tab_info['webSocketDebuggerUrl'] else: try: tab_info = None for current_tab_info in json.loads(call_method(self._host, self._port, 'list')): if current_tab_info['id'] == tab_id: tab_info = current_tab_info if tab_info is None: raise ValueError('Tab {0} not found'.format(tab_id)) self._id = tab_info['id'] self._ws_url = tab_info['webSocketDebuggerUrl'] except: self._id = tab_id self._ws_url = 'ws://{0}:{1}/devtools/page/{2}'.format(self._host, self._port, tab_id) self._soc = websocket.create_connection(self._ws_url) self._i = 0 self._tabs = tabs
def _connect(self, port): """Connect to the websocket, retrying as needed. Returns the socket.""" was_running = False for i in range(120): is_running = self.running was_running = was_running or is_running if (i >= 30 or was_running) and not is_running: logging.warning( "SC2 isn't running, so bailing early on the websocket connection.") break logging.info("Connection attempt %s (running: %s)", i, is_running) time.sleep(1) try: return websocket.create_connection("ws://127.0.0.1:%s/sc2api" % port, timeout=2 * 60) # 2 minutes except socket.error: pass # SC2 hasn't started listening yet. except websocket.WebSocketException as err: if "Handshake Status 404" in str(err): pass # SC2 is listening, but hasn't set up the /sc2api endpoint yet. else: raise sys.exit("Failed to create the socket.")
def connect(self): if not self.connected and not self.connecting: self.connecting = True if self.ws_url: try: ws = create_connection(self.ws_url, sslopt=sslopt_ca_certs) self.hook = w.hook_fd(ws.sock._sock.fileno(), 1, 0, 0, "receive_ws_callback", self.get_team_hash()) ws.sock.setblocking(0) self.ws = ws # self.attach_websocket(ws) self.set_connected() self.connecting = False except Exception as e: dbg("websocket connection error: {}".format(e)) self.connecting = False return False else: # The fast reconnect failed, so start over-ish for chan in self.channels: self.channels[chan].got_history = False s = SlackRequest(self.token, 'rtm.start', {}, retries=999) self.eventrouter.receive(s) self.connecting = False # del self.eventrouter.teams[self.get_team_hash()] self.set_reconnect_url(None)
def _ws_loop(self, gateway): self._status = Status.CONNECTING self._ws = create_connection(gateway) self._seq = 0 self._send(PacketBuilder.identify(self._client.api_client.token)) initial_packet = self._recv() self._on_initial_packet(initial_packet) self._on_packet(initial_packet) try: while True: packet = self._recv() self._on_packet(packet) finally: if self._heartbeat_greenlet: self._heartbeat_greenlet.kill() self._ws_greenlet = None
def connect(self, room): """ connect(room) -> Bool Connect to the given room. Cannot send messages without first connecting. """ self.room = room url = "wss://%s/room/%s/ws" % (self.site, self.room) try: self.socket = websocket.create_connection(url, enable_multithread=True, timeout=40) except (websocket.WebSocketException, IOError): self.socket = None return False return True
def start(self): last_event_time = self.browser.rooms[self.room_id]['eventtime'] ws_auth_data = self.browser.post_fkeyed( 'ws-auth', {'roomid': self.room_id} ).json() wsurl = ws_auth_data['url'] + '?l=%s' % (last_event_time,) self.logger.debug('wsurl == %r', wsurl) self.ws = websocket.create_connection( wsurl, origin=self.browser.chat_root) self.thread = threading.Thread(target=self._runner) self.thread.setDaemon(True) self.thread.start()
def play_net(model, params): ws = create_connection("ws://localhost:8000/ws") welcomeJson = ws.recv() welcome = json.loads(welcomeJson) clientId = welcome['snakeID'] while True: state = ws.recv() parsed = json.loads(state) if parsed['eventType'] != 'World': continue qval = model.predict(world_json_to_array(parsed['world'], clientId), batch_size=1) action = (np.argmax(qval)) # best ws.send(json.dumps({"actionType": "Direction", "snakeID": clientId, "direction": intToDirection(action)}))
def _create_connection(self): """ Create a new websocket connection with proper headers. """ logging.debug("Initializing new websocket connection.") headers = { 'Authorization': self.service._get_bearer_token(), 'Predix-Zone-Id': self.ingest_zone_id, 'Content-Type': 'application/json', } url = self.ingest_uri logging.debug("URL=" + str(url)) logging.debug("HEADERS=" + str(headers)) # Should consider connection pooling and longer timeouts return websocket.create_connection(url, header=headers)
def test_cells(self, nb_test_case): # Execute all code cells in a notebook code entity, get the response message in JSON format, # and return all code cells parsed by messages in a list. errors = 0 ws_url = nb_test_case.elyra_client.get_ws_kernel_endpoint(self.kernel_id) ws = websocket.create_connection(url=ws_url, timeout=itest_cell_timeout) print("Connection created for web socket {}".format(ws_url)) try: code_cell_count = 1 for code_cell in self.code_cell_list: if code_cell.is_executed(): errors = errors + NBCodeEntity.test_cell(nb_test_case, ws, code_cell, code_cell_count) code_cell_count = code_cell_count+1 finally: ws.close() return errors
def __init__(self, name, url, code): """Initialize the media player.""" from websocket import create_connection self._connection = create_connection self._url = url self._authorization_code = code self._name = name self._status = STATE_OFF self._ws = None self._title = None self._artist = None self._albumart = None self._seek_position = None self._duration = None self._volume = None self._request_id = 0 self.update()
def _open_new_tab(self): url = ChromeAPI.OPEN_NEW_TAB_URL.format(self._host, self._port) try: response = requests.get(url) except Exception as e: print("Error while access {0}, please check chrome browser.".format(url)) print("Details error: {0}".format(e)) return False response = response.json() tab_id = response.get("id") if not tab_id: return False ws_url = response.get("webSocketDebuggerUrl") if not ws_url: return False ws_instance = websocket.create_connection(ws_url, timeout=self._timeout) if not ws_instance: return False self._tab = { "tab_id": tab_id, "ws_url": ws_url, "ws_instance": ws_instance } return self._tab
def __init__(self, url, ip="127.0.0.1", port="9222", cookie="", post="", auth=""): """ ??? :param url: ??url :param ip: ChromeHeadless?server ip :param port: ChromeHeadless?server ?? :param cookie: ??cookie :param post: ??post Chrome?api??? :param auth: ?? authorization """ self.url = url self.cookie = cookie self.post = post self.auth = auth self.ip = ip self.port = port self.tab_id = "" self.ws_url = "" self.hook_urls = [] self.error = "" self.soc = None self.javascript_dialog_events = [] chrome_web = "http://%s:%s/json/new" % (ip, port) try: response = requests.get(chrome_web) self.ws_url = response.json().get("webSocketDebuggerUrl") self.tab_id = response.json().get("id") self.soc = websocket.create_connection(self.ws_url) # print(self.ws_url, self.tab_id) except Exception, e: # print "ERROR:%s" % e self.error = str(e)
def send_msg(self, id, method, params): """ ?ChromeHeadless?server ????? :param id: :param method: :param params: :return: """ # soc = websocket.create_connection(ws_url) navcom = json.dumps({ "id": id, "method": method, "params": params }) self.soc.send(navcom)
def auth_rockets(): global rockets_ws print('Attempting to connect to rockets...') rockets_ws = create_connection("ws://rockets.cc:3210") rockets_ws.send(rockets_subscription) print('Success!') # downloads an image from imgur # returns: image path
def create_slack_websocket(self, data): web_socket_url = data['url'] try: self.ws = create_connection(web_socket_url, sslopt=sslopt_ca_certs) self.ws_hook = w.hook_fd(self.ws.sock._sock.fileno(), 1, 0, 0, "slack_websocket_cb", self.identifier) self.ws.sock.setblocking(0) return True except Exception as e: print("websocket connection error: {}".format(e)) return False
def __init__(self, userid, username, mode="1v1", gameid=None, force_start=True, region=None): logging.debug("Creating connection") self._ws = create_connection(_ENDPOINT) self._lock = threading.RLock() logging.debug("Starting heartbeat thread") _spawn(self._start_sending_heartbeat) logging.debug("Joining game") self._send(["set_username", userid, username]) if mode == "private": if gameid is None: raise ValueError("Gameid must be provided for private games") self._send(["join_private", gameid, userid]) elif mode == "1v1": self._send(["join_1v1", userid]) elif mode == "team": if gameid is None: raise ValueError("Gameid must be provided for team games") self._send(["join_team", gameid, userid]) elif mode == "ffa": self._send(["play", userid]) else: raise ValueError("Invalid mode") self._send(["set_force_start", gameid, force_start]) self._seen_update = False self._move_id = 1 self._start_data = {} self._stars = [] self._map = [] self._cities = []
def get_remote_topic_type(topic_name, url): while True: try: ws = websocket.create_connection(url) break except Exception, e: rospy.loginfo('Create connection to Rosbridge server %s failed, retrying. Reason: %s', url, str(e)) time.sleep(2) try: # get topic type ws.send(json.dumps({ 'op': 'call_service', 'service': '/rosapi/topic_type', 'args': [topic_name] })) x = json.loads(ws.recv()) assert x['service'] == '/rosapi/topic_type' ws.close() if x['result']: return x['values']['type'] else: return "" except Exception, e: rospy.logerr('Get the type of topic %s from Rosbridge server %s failed. Reason: %s', topic_name, url, str(e)) ws.close() return ""
def get_remote_service_info(service_name, url): while True: try: ws = websocket.create_connection(url) break except Exception, e: rospy.loginfo('Create connection to Rosbridge server %s failed, retrying. Reason: %s', url, str(e)) time.sleep(2) try: # get topic type ws.send(json.dumps({ 'op': 'call_service', 'service': '/rosapi/service_type', 'args': [service_name] })) x = json.loads(ws.recv()) assert x['service'] == '/rosapi/service_type' ws.close() if x['result']: return x['values']['type'] else: return "" except Exception, e: rospy.logerr('Get the type of service %s from Rosbridge server %s failed. Reason: %s', service_name, url, str(e)) ws.close() return ""
def execute_command(self, command): from modules.bot import bot_msg print("Link:", self.request) youtube_id = self.get_link_id(self.request) print("ID:", youtube_id) # if(database.db_add_song_request(youtube_id, self.user)): response = self.get_song_request(youtube_id) bot_msg(response) # send to db: # user, id, timestamp, position (get this on insert) # test stuff # ws = create_connection("ws://localhost:3001", subprotocols=["echo-protocol"]) # print("Sending 'Hello world!'") # ws.send("Hello, world!")
def connect(self): url = self.host_url try: self.ws = websocket.create_connection(url, skip_utf8_validation=True) except socket.error as e: raise exception.ConnectionFailed(e) except websocket.WebSocketConnectionClosedException as e: raise exception.ConnectionFailed(e) except websocket.WebSocketBadStatusException as e: raise exception.ConnectionFailed(e)
def testIter(self): count = 2 for rsvp in ws.create_connection('ws://stream.meetup.com/2/rsvps'): count -= 1 if count == 0: break
def testNext(self): sock = ws.create_connection('ws://stream.meetup.com/2/rsvps') self.assertEqual(str, type(next(sock)))
def testWebSocket(self): s = ws.create_connection("ws://echo.websocket.org/") self.assertNotEqual(s, None) s.send("Hello, World") result = s.recv() self.assertEqual(result, "Hello, World") s.send(u"??????????") result = s.recv() self.assertEqual(result, "??????????") s.close()
def testPingPong(self): s = ws.create_connection("ws://echo.websocket.org/") self.assertNotEqual(s, None) s.ping("Hello") s.pong("Hi") s.close()
def testSecureWebSocket(self): if 1: import ssl s = ws.create_connection("wss://echo.websocket.org/") self.assertNotEqual(s, None) self.assertTrue(isinstance(s.sock, ssl.SSLSocket)) s.send("Hello, World") result = s.recv() self.assertEqual(result, "Hello, World") s.send(u"??????????") result = s.recv() self.assertEqual(result, "??????????") s.close() #except: # pass
def testAfterClose(self): s = ws.create_connection("ws://echo.websocket.org/") self.assertNotEqual(s, None) s.close() self.assertRaises(ws.WebSocketConnectionClosedException, s.send, "Hello") self.assertRaises(ws.WebSocketConnectionClosedException, s.recv)
def testSockOpt(self): sockopt = ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),) s = ws.create_connection("ws://echo.websocket.org", sockopt=sockopt) self.assertNotEqual(s.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0) s.close()
def testWebSocketWihtCustomHeader(self): s = ws.create_connection("ws://echo.websocket.org/", headers={"User-Agent": "PythonWebsocketClient"}) self.assertNotEqual(s, None) s.send("Hello, World") result = s.recv() self.assertEqual(result, "Hello, World") s.close()
def _process_data(self): self.conn = create_connection(self.addr, timeout=4) for pair in self.pairs: payload = [{'event': 'addChannel', 'channel': 'ok_sub_spotusd_%s_ticker' % pair}, {'event': 'addChannel', 'channel': 'ok_sub_spotusd_%s_depth_60' % pair}, {'event': 'addChannel', 'channel': 'ok_sub_spotusd_%s_trades' % pair}, {'event': 'addChannel', 'channel': 'ok_sub_spotusd_%s_kline_1min' % pair}] log.debug(payload) self.conn.send(json.dumps(payload)) while self.running: try: data = json.loads(self.conn.recv()) except (WebSocketTimeoutException, ConnectionResetError): self._controller_q.put('restart') if 'data' in data: pair = ''.join(data['channel'].split('spot')[1].split('_')[:2]).upper() self.data_q.put((data['channel'], pair, data['data'], time.time())) else: log.debug(data) self.conn = None
def _process_data(self): self.conn = create_connection(self.addr, timeout=4) payload = json.dumps({'type': 'subscribe', 'product_ids': self.pairs}) self.conn.send(payload) while self.running: try: data = json.loads(self.conn.recv()) except (WebSocketTimeoutException, ConnectionResetError): self._controller_q.put('restart') if 'product_id' in data: self.data_q.put(('order_book', data['product_id'], data, time.time())) self.conn = None
def start(self): """ Start the websocket client threads :return: """ super(BitfinexWSS, self).start() log.info("BitfinexWSS.start(): Initializing Websocket connection..") while self.conn is None: try: self.conn = create_connection(self.addr, timeout=10) except WebSocketTimeoutException: self.conn = None print("Couldn't create websocket connection - retrying!") log.info("BitfinexWSS.start(): Initializing receiver thread..") if not self.receiver_thread: self.receiver_thread = Thread(target=self.receive, name='Receiver Thread') self.receiver_thread.start() else: log.info("BitfinexWSS.start(): Thread not started! " "self.receiver_thread is populated!") log.info("BitfinexWSS.start(): Initializing processing thread..") if not self.processing_thread: self.processing_thread = Thread(target=self.process, name='Processing Thread') self.processing_thread.start() else: log.info("BitfinexWSS.start(): Thread not started! " "self.processing_thread is populated!") self.setup_subscriptions()
def _subscription_thread(self, endpoint): """ Thread Method, running the connection for each endpoint. :param endpoint: :return: """ try: conn = create_connection(self.addr + endpoint, timeout=5) except WebSocketTimeoutException: self.restart_q.put(endpoint) return while self.threads_running[endpoint]: try: msg = conn.recv() except WebSocketTimeoutException: self._controller_q.put(endpoint) log.debug("%s, %s", endpoint, msg) ep, pair = endpoint.split('/') log.debug("_subscription_thread(): Putting data on q..") try: self.data_q.put((ep, pair, msg, time.time()), timeout=1) except TimeoutError: continue finally: log.debug("_subscription_thread(): Data Processed, looping back..") conn.close() log.debug("_subscription_thread(): Thread Loop Ended.")
def ws_connect(self, path): return create_connection(self.format_path('ws', path))
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()