Python websockets 模块,connect() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用websockets.connect()

项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
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,
        }
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def _connect(self, endpoints):
        if len(endpoints) == 0:
            raise Exception('no endpoints to connect to')
        first_exception = None
        # TODO try connecting concurrently.
        for endpoint, cacert in endpoints:
            try:
                self.ws, self.addr = await self._open(endpoint, cacert)
                self.endpoint = endpoint
                self.cacert = cacert
                self._receiver_task.start()
                log.info("Driver connected to juju %s", self.addr)
                self.monitor.close_called.clear()
                return
            except Exception as e:
                if first_exception is None:
                    first_exception = e
        raise first_exception
项目:GrimREPL    作者:emehrkay    | 项目源码 | 文件源码
def query(self, script=None, params=None, rebindings=None, op='eval',
                    processor=None, language='gremlin-groovy', session=None):
        try:
            connection = websockets.connect(self.ws_uri)

            async with connection as ws:
                message = self.message(script=script, params=params,
                                       rebindings=rebindings, op=op,
                                       processor=processor, language=language,
                                       session=session)

                await ws.send(message)

                response = await ws.recv()

                return json.loads(response)
        except Exception as e:
            raise e
项目:globibot    作者:best-coloc-ever    | 项目源码 | 文件源码
def run_ws(self):
        self.debug('Connecting to PubSub service')

        async with websockets.connect(PubSub.WS_URL) as ws:
            self.ws = ws

            self.run_async(self.send_pings())
            self.run_async(self.process_pubsub_orders())

            while True:
                try:
                    message = await self.ws.recv()
                except:
                    break
                data = json.loads(message)

                await self.on_ws_data(data)

        self.ws = None
        self.service_started = False
        self.debug('Disconnected from PubSub service')
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_send_and_close_connection():
    async def app(message, channels):
        if message['channel'] == 'websocket.connect':
            await channels['reply'].send({'text': '123', 'close': True})

    async def get_data(url):
        async with websockets.connect(url) as websocket:
            data = await websocket.recv()
            is_open = True
            try:
                await websocket.recv()
            except:
                is_open = False
            return (data, is_open)

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        (data, is_open) = loop.run_until_complete(get_data(url))
        assert data == '123'
        assert not is_open
        loop.close()
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_send_binary_data_to_server():
    async def app(message, channels):
        if message['channel'] == 'websocket.connect':
            await channels['reply'].send({'accept': True})
        elif message['channel'] == 'websocket.receive':
            data = message.get('bytes')
            await channels['reply'].send({'bytes': data})

    async def send_text(url):
        async with websockets.connect(url) as websocket:
            await websocket.send(b'abc')
            return await websocket.recv()

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        data = loop.run_until_complete(send_text(url))
        assert data == b'abc'
        loop.close()
项目:parsec-cloud    作者:Scille    | 项目源码 | 文件源码
def open_connection(self, identity):
        logger.debug('Connection to backend opened')
        assert not self._websocket, "Connection to backend already opened"
        try:
            self._websocket = await websockets.connect(self.url)
            # Handle handshake
            raw = await self._websocket.recv()
            challenge = ejson_loads(raw)
            answer = identity.private_key.sign(challenge['challenge'].encode())
            await self._websocket.send(ejson_dumps({
                'handshake': 'answer',
                'identity': identity.id,
                'answer': to_jsonb64(answer)
            }))
            resp = ejson_loads(await self._websocket.recv())
            if resp['status'] != 'ok':
                await self.close_connection()
                raise exception_from_status(resp['status'])(resp['label'])
            self._ws_recv_handler_task = asyncio.ensure_future(
                self._ws_recv_handler(), loop=self.loop)
            if self.watchdog_time:
                self._watchdog_task = asyncio.ensure_future(self._watchdog(), loop=self.loop)
        except (ConnectionRefusedError, websockets.exceptions.ConnectionClosed) as exc:
            raise BackendConnectionError('Cannot connect to backend (%s)' % exc)
项目:webtiles    作者:gammafunk    | 项目源码 | 文件源码
def connect(self, websocket_url, username=None, password=None,
                protocol_version=1, *args, **kwargs):
        """Connect to the given websocket URL with optional credentials. Use a
        value of 2 for `protocol_version` on servers running the
        webtiles-changes branch. Additional arguments are passed to
        `webscokets.connect()`.

        """

        if username and not password:
            raise WebTilesError("Username given but no password given.")

        if self.connected():
            raise WebTilesError("Attempted to connect when already connected.")

        self.websocket = yield from websockets.connect(websocket_url, *args,
                                                       **kwargs)
        self.protocol_version = protocol_version
        if username:
            yield from self.send_login(username, password)
            self.login_user = username
项目:webtiles    作者:gammafunk    | 项目源码 | 文件源码
def send_login(self, username, password):
        """Send the login message. This is usally called by `connect()`, but the
        `send_login()` method can be used to authenticate after connecting
        without credentials. The `logged_in` property will only be True after
        the server responds with a "login_complete" message when this is
        handled by `handle_message()`.

        """

        msg = {"msg" : "login",
               "username" : username,
               "password" : password}
        # XXX We don't yet support cookie login in any protocol. This isn't
        # useful for any project using the library right now, but may be in the
        # future.
        if self.protocol_version >= 2:
            msg["rememberme"] = False
        yield from self.send(msg)
        self.logged_in = False
        self.login_user = username
项目:botcycle    作者:D2KLab    | 项目源码 | 文件源码
def main():
    while True:
        try:
            async with websockets.connect(websocket_location) as websocket:
                print('connected to botkit')
                sender_thread = threading.Thread(
                    target=send_messages, args=[websocket])
                sender_thread.daemon = True
                sender_thread.start()
                with ThreadPoolExecutor() as executor:
                    while True:
                        message = await get_message(websocket)
                        log_msg(message)
                        # execute directly to show stack on exceptions
                        # TODO reenable threading
                        botcycle.process(message, queue_message)

        except websockets.exceptions.ConnectionClosed as e:
            print(e)
        except OSError:
            print('unreachable botkit websocket')
        except Exception as e:
            traceback.print_exc()

        time.sleep(2)
项目:chromewhip    作者:chuckus    | 项目源码 | 文件源码
def attempt_tab_fetch(self):
        async with aiohttp.ClientSession() as session:
            async with session.get(self._url + '/json') as resp:
                tabs = []
                data = await resp.json()
                if not len(data):
                    self._log.warning('Empty data, will attempt to reconnect until able to get pages.')
                for tab in filter(lambda x: x['type'] == 'page', data):
                    ws_url = tab.get('webSocketDebuggerUrl')
                    if not ws_url:
                        tab_id = tab['id']
                        ws_url = 'ws://{}:{}/devtools/page/{}'.format(self._host,
                                                                      self._port,
                                                                      tab_id)
                    t = ChromeTab(tab['title'], tab['url'], ws_url)
                    await t.connect()
                    tabs.append(t)
                self._tabs = tabs
                self._log.debug("Connected to Chrome! Found {} tabs".format(len(self._tabs)))
        self.is_connected = True
项目:chrome_remote_interface_python    作者:wasiher    | 项目源码 | 文件源码
def __aenter__(self):
        self._soc = await websockets.connect(self._ws_url)
        async def loop():
            try:
                while 1:
                    resp = json.loads(await self._soc.recv())
                    if 'id' in resp:
                        self._method_responses[resp['id']] = resp
                        self._recv_data_lock[resp['id']].release()
                    elif 'method' in resp:
                        asyncio.ensure_future(self._run_later(self._handle_event(resp['method'], resp['params'])))
                    else:
                        raise RuntimeError('Unknown data came: {0}'.format(resp))
            except (websockets.ConnectionClosed, concurrent.futures.CancelledError):
                pass
            except Exception as e:
                traceback.print_exc()
        asyncio.ensure_future(self._run_later(loop()))
        return self
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def rm(args, websockets_path):
    assert args.account
    account = args.account[0]
    message = json.dumps({
        "command": "dw_delete_account",
        "id": create_random_id(),
        "params": [
            account
        ]
    })
    print("Sending:", message)
    async with websockets.connect(websockets_path) as websocket:
        await websocket.send(message)
        response = json.loads(await websocket.recv())
    print(response)
    return 0
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def setting(args, websockets_path):
    name = args.name[0]
    value = args.value
    if value is None:
        message = json.dumps({
            "command": "dw_get_setting",
            "id": create_random_id(),
            "params": [
                name
            ]
        })
    else:
        message = json.dumps({
            "command": "dw_set_setting",
            "id": create_random_id(),
            "params": [
                name,
                value
            ]
        })
    print("Sending:", message)
    async with websockets.connect(websockets_path) as websocket:
        await websocket.send(message)
        response = json.loads(await websocket.recv())
    print(response)
项目:beam-interactive-python-unofficial    作者:NatKarmios    | 项目源码 | 文件源码
def start(address, channel, key, loop=None):
    """Starts a new Interactive client.

    Takes the remote address of the Tetris robot, as well as the
    channel number and auth key to use. Additionally, it takes
    a list of handler. This should be a dict of protobuf wire
    IDs to handler functions (from the .proto package).
    """

    if loop is None:
        loop = asyncio.get_event_loop()

    socket = yield from websockets.connect(address+"/robot", loop=loop)

    conn = Connection(socket, loop)
    yield from conn.send_coro(_create_handshake(channel, key))

    return conn
项目:litecord-reference    作者:lnmds    | 项目源码 | 文件源码
def main():
    sess = aiohttp.ClientSession()
    gateway = None

    log.info(f'requesting {BASE}/gateway')
    async with sess.get(f'{BASE}/gateway') as r:
        gateway = await r.json()

    log.info('gateway: %r', gateway)
    ws = await websockets.connect(gateway['url'])
    log.info('in loop')
    try:
        while True:
            d = await ws.recv()
            log.info('data: %s', d)
    except KeyboardInterrupt:
        await ws.close()
项目:slack-today-i-did    作者:eeue56    | 项目源码 | 文件源码
def __aenter__(self):
        reply = self.server.api_requester.do(self.token, "rtm.start")

        if reply.status_code != 200:
            raise SlackConnectionError
        else:
            login_data = reply.json()

            if login_data["ok"]:
                self.ws_url = login_data['url']
                if not self._should_reconnect:
                    self.server.parse_slack_login_data(login_data)
                self._conn = websockets.connect(self.ws_url, ssl=ssl_context)
            else:
                raise SlackLoginError

        self.websocket = await self._conn.__aenter__()
        return self
项目:Tarnished-Tale    作者:ZAdamMac    | 项目源码 | 文件源码
def authenticate(tgt):  # sends the authentication message to sock
    global instanceContext
    async with ws.connect(tgt, ssl=instanceContext) as sock:
        socket = sock
        print("Connection successful at %s" % tgt)
        msg =await sock.recv()
        print(msg)
        global authed; authed = False

        while not authed:
            user = input("Username:")
            pwd = input("Password:")
            msg = ("ATERM_MSG %s %s" % (user, pwd))
            await sock.send(msg)
            resp = await sock.recv()
            print(resp)
            if resp == "Authentication Successful, you are now the admin terminal.":
                authed = True
                await asyncio.gather(remoteListen(sock), stdinListen(sock))
            else:
                authed = False

#Runtime
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def _open(self, endpoint, cacert):
        if self.uuid:
            url = "wss://{}/model/{}/api".format(endpoint, self.uuid)
        else:
            url = "wss://{}/api".format(endpoint)

        return (await websockets.connect(
            url,
            ssl=self._get_ssl(cacert),
            loop=self.loop,
            max_size=self.max_frame_size,
        ), url)
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def clone(self):
        """Return a new Connection, connected to the same websocket endpoint
        as this one.

        """
        return await Connection.connect(**self.connect_params())
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
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,
        )
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
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
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
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')
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
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
项目:chrome-prerender    作者:bosondata    | 项目源码 | 文件源码
def attach(self) -> None:
        logger.debug('Connecting to %s', self.websocket_debugger_url)
        self.websocket = await websockets.connect(
            self.websocket_debugger_url,
            max_size=5 * 2 ** 20,  # 5M
            loop=self.loop,
        )

        self.on('Inspector.detached', self._on_inspector_detached)
        self.on('Inspector.targetCrashed', self._on_inspector_target_crashed)
        self.on('Log.entryAdded', self._on_log_entry_added)
        self.on('Network.requestWillBeSent', self._on_request_will_be_sent)
        self.on('Network.responseReceived', self._on_response_received)
        self.on('Network.loadingFailed', self._on_response_received)

        self.on('Network.dataReceived', self._update_last_active_time)
        self.on('Network.resourceChangedPriority', self._update_last_active_time)
        self.on('Network.webSocketWillSendHandshakeRequest', self._update_last_active_time)
        self.on('Network.webSocketHandshakeResponseReceived', self._update_last_active_time)
        self.on('Network.webSocketCreated', self._update_last_active_time)
        self.on('Network.webSocketClosed', self._update_last_active_time)
        self.on('Network.webSocketFrameReceived', self._update_last_active_time)
        self.on('Network.webSocketFrameError', self._update_last_active_time)
        self.on('Network.webSocketFrameSent', self._update_last_active_time)
        self.on('Network.eventSourceMessageReceived', self._update_last_active_time)
        self.on('Page.domContentEventFired', self._update_last_active_time)
        self.on('Page.frameAttached', self._update_last_active_time)
        self.on('Page.frameNavigated', self._update_last_active_time)
        self.on('Page.frameDetached', self._update_last_active_time)
        self.on('Page.frameStartedLoading', self._update_last_active_time)
        self.on('Page.frameStoppedLoading', self._update_last_active_time)
        self.on('DOM.documentUpdated', self._update_last_active_time)

        self._ws_task = asyncio.ensure_future(self._listen())
        await asyncio.wait_for(self._enable_events(), timeout=5)
        if self.user_agent is not None:
            await self.set_user_agent(self.user_agent)
        await self.set_blocked_urls(BLOCKED_URLS)
项目:Tuxemon-Server    作者:Tuxemon    | 项目源码 | 文件源码
def hello():
    async with websockets.connect('ws://localhost:9000/') as websocket:

        name = input("What's your name? ")
        await websocket.send(name)
        print("> {}".format(name))

        greeting = await websocket.recv()
        print("< {}".format(greeting))
项目:arc    作者:lap00zza    | 项目源码 | 文件源码
def ws_client(self):
        self.ws = await websockets.connect("ws://ws_server:5555")
        while True:
            greeting = await self.ws.recv()
            # print("< {}".format(greeting))

    # Override :class:`Thread` 's start method and start our
    # websocket thread. We will keep a single thread running
    # for this task.
项目:arc    作者:lap00zza    | 项目源码 | 文件源码
def __init__(self):
        Flask.__init__(self, __name__)

        # Auth Initialization
        # NOTE: To invalidate all JWT's just change this secret.
        self.auth = Auth(os.environ.get("JWT_SECRET"), "HS256")

        # Database initialization
        self.db = DB()
        self.db.connect()

        # Register the routes
        # TODO: message rate limit 10 per 5 second
        self.route("/api", methods=["GET", "POST"])(self.index)
        self.route("/api/v1/myInfo", methods=["GET"])(self.my_info)
        self.route("/api/v1/channel/<channel_id>/messages", methods=["POST"])(self.messages)
        self.route("/api/v1/auth/login", methods=["POST"])(self.login)
        self.route("/api/v1/auth/register", methods=["POST"])(self.register)

        # start the ws client thread
        self.ws_client = WSClient()
        self.ws_client.start()

        # TODO: this is temporary redis replacement. Remove it later.
        self.mem_store = MemStore()

    # --- HELPER METHODS ---
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_accept_connection():
    async def app(message, channels):
        await channels['reply'].send({'accept': True})

    async def open_connection(url):
        async with websockets.connect(url) as websocket:
            return websocket.open

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        is_open = loop.run_until_complete(open_connection(url))
        assert is_open
        loop.close()
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_reject_connection():
    async def app(message, channels):
        await channels['reply'].send({'accept': False})

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        with pytest.raises(websockets.exceptions.InvalidHandshake):
            state = loop.run_until_complete(websockets.connect(url))
        loop.close()
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_send_text_data_to_client():
    async def app(message, channels):
        if message['channel'] == 'websocket.connect':
            await channels['reply'].send({'text': '123'})

    async def get_data(url):
        async with websockets.connect(url) as websocket:
            return await websocket.recv()

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        data = loop.run_until_complete(get_data(url))
        assert data == '123'
        loop.close()
项目:uvicorn    作者:encode    | 项目源码 | 文件源码
def test_send_binary_data_to_client():
    async def app(message, channels):
        if message['channel'] == 'websocket.connect':
            await channels['reply'].send({'bytes': b'123'})

    async def get_data(url):
        async with websockets.connect(url) as websocket:
            return await websocket.recv()

    with run_server(app) as url:
        loop = asyncio.new_event_loop()
        data = loop.run_until_complete(get_data(url))
        assert data == b'123'
        loop.close()
项目:python-mattermost-driver    作者:Vaelor    | 项目源码 | 文件源码
def connect(self, event_handler):
        """
        Connect to the websocket and authenticate it.
        When the authentication has finished, start the loop listening for messages,
        sending a ping to the server to keep the connection alive.
        :param event_handler: Every websocket event will be passed there
        :type event_handler: Function
        :return:
        """
        context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
        if not self.options['verify']:
            context.verify_mode = ssl.CERT_NONE

        scheme = 'wss://'
        if self.options['scheme'] != 'https':
            scheme = 'ws://'
            context = None

        url = scheme + self.options['url'] + ':' + str(self.options['port']) + self.options['basepath'] + '/websocket'

        websocket = yield from websockets.connect(
            url,
            ssl=context,
        )

        yield from self._authenticate_websocket(websocket, event_handler)
        yield from self._start_loop(websocket, event_handler)
项目:parsec-cloud    作者:Scille    | 项目源码 | 文件源码
def connect_event(self, event, sender, cb):
        msg = {'cmd': 'subscribe', 'event': event, 'sender': sender}
        await self.send_cmd(msg)
        self._signal_ns.signal(event).connect(cb, sender=sender)
项目:parsec-cloud    作者:Scille    | 项目源码 | 文件源码
def ping(self):
        assert self._websocket, "Connection to backend not opened"
        try:
            await self._websocket.ping()
        except websockets.exceptions.ConnectionClosed as exc:
            raise BackendConnectionError('Cannot connect to backend (%s)' % exc)
项目:parsec-cloud    作者:Scille    | 项目源码 | 文件源码
def send_cmd(self, msg):
        if not self._websocket:
            raise BackendConnectionError('BackendAPIService cannot send command in current state')
        try:
            await self._websocket.send(ejson_dumps(msg))
        except websockets.exceptions.ConnectionClosed as exc:
            raise BackendConnectionError('Cannot connect to backend (%s)' % exc)
        ret = await self._resp_queue.get()
        status = ret['status']
        if status == 'ok':
            return ret
        else:
            raise exception_from_status(status)(ret['label'])
项目:async-skeleton-murder    作者:Euphe    | 项目源码 | 文件源码
def client():
    global websocket
    websocket = await websockets.connect('ws://{}:{}'.format(HOST, PORT))
    asyncio.ensure_future(handle_reading(websocket))
    asyncio.ensure_future(handle_sending(websocket))
项目:highway.py    作者:PhilipTrauner    | 项目源码 | 文件源码
def client(self, address, port, wss):
        async with connect("ws%s://%s:%i" % ("s" if wss else "", 
            address, port)) as websocket:

            await self.consumer(websocket)
项目:GLaDOS2    作者:TheComet    | 项目源码 | 文件源码
def __connect(self, bridge):
        conn = http.client.HTTPSConnection(API_URL)

        # Look up user_id, which apparently is also the channel_id
        user_name = bridge['user name']
        conn.request('GET', API_V + '/channel/name/{}'.format(user_name))
        response = conn.getresponse()
        if response.status != 200:
            glados.log('Failed to retrieve channel_id from /channel/name/{}\n{} {}\n{}'.format(
                user_name, response.status, response.reason, response.read()))
            return None
        channel_id = json.loads(response.read().decode('utf-8'))['user_id']

        # With channel_id, generate JWT key
        params = {'channel_id': channel_id, 'bot': True}
        headers = {'Authorization': 'Bearer {}'.format(self.settings['picarto']['persistent token'])}
        conn.request('GET', API_V + '/user/jwtkey?{}'.format(urllib.parse.urlencode(params)), headers=headers)
        response = conn.getresponse()
        if response.status != 200:
            glados.log('Failed to generate JWT key\n{} {}\n{}'.format(
                response.status, response.reason, response.read()))
            return None
        jwt_key = response.read().decode('utf-8')

        conn.close()

        url = CHAT_ENDPOINT.format(jwt_key)
        websocket = asyncio.get_event_loop().run_until_complete(websockets.connect(url))
        client = PicartoClient(self.client, bridge['discord channel id'], websocket)
        return client
项目:chunnel    作者:obmarg    | 项目源码 | 文件源码
def run(self):
        try:
            async with websockets.connect(self.url) as websocket:
                self.ready.set_result(True)
                # TODO: Think about error propagation at some point?
                # If one of these crashes, does it cancel the other?
                # It should, not sure if it does.
                await asyncio.gather(
                    self._recv_loop(websocket), self._send_loop(websocket)
                )
        except Exception as e:
            if not self.ready.done():
                self.ready.set_exception(e)

            raise
项目:streamtotext    作者:ibm-dev    | 项目源码 | 文件源码
def _start(self):
        connect_url = 'wss://%s/%s' % (self._host, self._uri_base)
        auth_header = self._to_auth_header(self._user, self._passwd)
        self._ws = await websockets.connect(
            connect_url,
            extra_headers={'Authorization': auth_header}
        )
        await self._send_start(self._ws, self._source_freq)
        await super(WatsonTranscriber, self)._start()
项目:pokemonai    作者:rishihahs    | 项目源码 | 文件源码
def run():
    async with websockets.connect(SMOGON_WEBSOCKET_URI) as websocket:
        await _connect(websocket)

        while True:
            while len(pool) < MAX_PARALLEL_GAMES:
                # Preload connection for battle so that it receives messages
                conn = await _open_connection()

                # Start Smogon battle search
                await websocket.send('|/utm %s' % SMOGON_TEAM)
                await websocket.send('|/search gen71v1')

                # Wait for battle initialization
                msg = ''
                while not '|init|battle' in msg:
                    msg = await websocket.recv()

                # Room id is in the first line of the message
                # of the form >roomid
                m = re.match('>(.+?)\n', msg)
                roomid = m.group(1)

                # Start battle handler with preloaded connection
                bh = BattleHandler(roomid, SMOGON_USERNAME)
                pool.add(asyncio.ensure_future(_battle(conn, bh)))

            # Wait for battle handlers to complete
            done, _ = await asyncio.wait(pool, return_when=asyncio.FIRST_COMPLETED)

            # Remove done from pool
            for d in done:
                pool.remove(d)
项目:pokemonai    作者:rishihahs    | 项目源码 | 文件源码
def _open_connection():
    websocket = await websockets.connect(SMOGON_WEBSOCKET_URI)
    await _connect(websocket)
    return websocket
项目:chromewhip    作者:chuckus    | 项目源码 | 文件源码
def connect(self):
        self._ws = await websockets.connect(self._ws_uri, max_size=MAX_PAYLOAD_SIZE_BYTES)  # 16MB
        self._recv_task = asyncio.ensure_future(self.recv_handler())
        self._log.info('Connected to Chrome tab %s' % self._ws_uri)
项目:chromewhip    作者:chuckus    | 项目源码 | 文件源码
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')
项目:chromewhip    作者:chuckus    | 项目源码 | 文件源码
def tabs(self):
        if not len(self._tabs):
            raise ValueError('Must call connect_s or connect first!')
        return tuple(self._tabs)
项目:KSURCT-TEST    作者:jisaiahgarrett    | 项目源码 | 文件源码
def SendMessage():
    websocket = await websockets.connect('ws://10.243.193.47:8055/')  # zerotier IP of server
    try:
        while True:
            controller.update()
            l_stick = round(controller.left_x(), 1)
            r_stick = round(controller.right_y(), 1)
            robot = {}
            oldRobot = {}
            robot['x'] = 1 if controller.x() else 0
            robot['y'] = 1 if controller.y() else 0
            robot['a'] = 1 if controller.a() else 0
            robot['b'] = 1 if controller.b() else 0
            robot['fwd'] = int(controller.right_trigger() >> 3)  # To implement turning, we will want to grab the left stick and adjust Fwd/Rev appropriately.
            robot['rev'] = int(controller.left_trigger() >> 3)
            robot['lstick'] = int(10*l_stick) if abs(l_stick) > 0.1 else 0
            robot['vision'] = 1 if str(controller.hat).strip() == 'd' else 0
            robot['peek'] = 1 if str(controller.hat).strip() == 'u' else 0
            robot['rstick'] = int(-10*r_stick) if abs(r_stick) > 0.1 else 0
            robot['lbump'] = 1 if controller.left_bumper() else 0

            # This needs testing, but logic seems in order.
            robot['lbx'] = 1 if controller.left_bumper() and controller.x() else 0
            robot['lbb'] = 1 if controller.left_bumper() and controller.b() else 0
            robot['lby'] = 1 if controller.left_bumper() and controller.y() else 0
            robot['lba'] = 1 if controller.left_bumper() and controller.a() else 0
            robot['rby'] = 1 if controller.right_bumper() and controller.y() else 0
            robot['rba'] = 1 if controller.right_bumper() and controller.a() else 0
            # If leftStick.X < 0 then we want to trim off the left motor to turn left.
            # If leftStick.X > 0 then we want to trim off the right motor to turn right.
            robot['valid'] = 1  # Was testing not spamming controller but that is impossible.

            if(robot):
                print(robot)
                await websocket.send(pickle.dumps(robot))
                oldRobot = robot
            with suppress(asyncio.TimeoutError):
                response = await asyncio.wait_for(websocket.recv(), 1)

    finally:
        await websocket.close()
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def restore(args, websockets_path):
    assert args.account
    account = args.account[0]
    #brainwallet = input("Brainwallet: ").split(" ")
    brainwallet = ['install', 'oppose', 'unique', 'steel', 'opera', 'next',
                   'add', 'town', 'warfare', 'leave', 'salt', 'chimney']
    #password = enter_confirmed_password()
    password = "surfing2"
    if password is None:
        print("Passwords don't match.")
        return -1
    message = json.dumps({
        "command": "dw_restore_account",
        "id": create_random_id(),
        "params": [
            account,
            brainwallet,
            password,
            args.testnet
        ]
    })
    print("Sending:", message)
    async with websockets.connect(websockets_path) as websocket:
        await websocket.send(message)
        response = json.loads(await websocket.recv())
    print(response)
    return 0
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def valid_addr(args, websockets_path):
    assert args.address
    message = json.dumps({
        "command": "dw_validate_address",
        "id": create_random_id(),
        "params": [
            args.address[0]
        ]
    })
    print("Sending:", message)
    async with websockets.connect(websockets_path) as websocket:
        await websocket.send(message)
        response = json.loads(await websocket.recv())
    print(response)
    return 0
项目:DarkWallet    作者:DissentDifference    | 项目源码 | 文件源码
def get_height(args, websockets_path):
    message = json.dumps({
        "command": "dw_get_height",
        "id": api.create_random_id(),
        "params": [
        ]
    })
    print("Sending:", message)
    async with websockets.connect(websockets_path) as websocket:
        await websocket.send(message)
        response = json.loads(await websocket.recv())
    print(response)
    return 0