How to use the websockets.client.WebSocketClientProtocol function in websockets

To help you get started, we’ve selected a few websockets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github steemit / jussi / tests / test_ws.py View on Github external
"previous": "000003e7c4fd3221cf407efcf7c1730e2ca54b05",
            "timestamp": "2016-03-24T16:55:30",
            "witness": "initminer",
            "transaction_merkle_root": "0000000000000000000000000000000000000000",
            "extensions": [],
            "witness_signature": "207f15578cac20ac0e8af1ebb8f463106b8849577e21cca9fc60da146d1d95df88072dedc6ffb7f7f44a9185bbf9bf8139a5b4285c9f423843720296a44d428856",
            "transactions": [],
            "block_id": "000003e8b922f4906a45af8e99d86b3511acd7a5",
            "signing_key": "STM8GC13uCZbP44HzMLV6zPZGwVQ8Nt4Kji8PapsPiNq1BK153XTX",
            "transaction_ids": []
        }
    }

    with asynctest.patch('jussi.ws.pool.Pool') as mocked_pool:
        mocked_ws_conn = asynctest.MagicMock(
            spec=websockets.client.WebSocketClientProtocol)
        mocked_ws_conn.recv.return_value = expected
        mocked_pool.acquire.return_value = mocked_ws_conn
        response = await test_cli.post('/', json=request)
        assert await response.json() == expected
github sammchardy / python-binance-chain / binance_chain / websockets.py View on Github external
def __init__(self, loop, coro, env: BinanceEnvironment):
        self._loop = loop
        self._log = logging.getLogger(__name__)
        self._coro = coro
        self._reconnect_attempts: int = 0
        self._conn = None
        self._env = env
        self._connect_id: int = None
        self._ping_timeout = 60
        self._socket: Optional[ws.client.WebSocketClientProtocol] = None

        self._connect()
github sharkbound / PythonTwitchBotFramework / twitchbot / pubsub / pubsub_client.py View on Github external
def __init__(self):
        self.socket: Optional[websockets.client.WebSocketClientProtocol] = None
        self.listen_count = 0
github ontio / ontology-python-sdk / ontology / network / websocket.py View on Github external
async def close_connect(self):
        if isinstance(self.__ws_client, client.WebSocketClientProtocol) and not self.__ws_client.closed:
            await self.__ws_client.close()
github snth / numismatic / numismatic / feeds / base.py View on Github external
async def _connect(self):
        '''
            Connects to websocket. Uses a future to ensure that only one
            connection at a time will happen
        '''
        if self.websocket is None or \
                isinstance(self.websocket, WebSocketClientProtocol) and \
                not self.websocket.open:
            logger.info(f'Connecting to {self.websocket_url!r} ...')
            self.websocket = \
                asyncio.ensure_future(websockets.connect(self.websocket_url))
        if isinstance(self.websocket, asyncio.Future):
            self.websocket = await self.websocket
github summa-tx / riemann-ether / ether / infura.py View on Github external
try:
        return hex(cast(int, number))
    except TypeError:
        return cast(str, number)


def _id():
    '''Infinite generator for unique request IDs'''
    index = 0
    while 1:
        yield index
        index += 1


URI = 'wss://{network}.infura.io/ws/v3/{project_id}'
_SOCKETS: Dict[str, WebSocketClientProtocol] = {}  # sockets open
_INFLIGHT: Dict[int, asyncio.Future] = {}  # requests awaiting responses
_SUBSCRIPTIONS: Dict[str, asyncio.Queue] = {}  # subscription queues
_IDS = _id()


async def close_socket(ws: WebSocketClientProtocol) -> None:
    await ws.close()


async def close_sockets() -> None:
    '''close all open connections'''
    global _SOCKETS
    tmp = _SOCKETS
    _SOCKETS = {}
    await asyncio.gather(*[close_socket(tmp[n]) for n in tmp])
github sammchardy / python-idex / idex / asyncio / websockets.py View on Github external
def __init__(self, loop, coro, api_key):
        self._loop = loop
        self._log = logging.getLogger(__name__)
        self._coro = coro
        self._reconnect_attempts: int = 0
        self._conn = None
        self._socket: ws.client.WebSocketClientProtocol = None
        self._sid: str = None
        self._handshaken: bool = False
        self._api_key = api_key

        self._connect()
github Deivedux / Quote / discord / gateway.py View on Github external
ack_time = time.perf_counter()
        self._last_ack = ack_time
        self.latency = ack_time - self._last_send

class VoiceKeepAliveHandler(KeepAliveHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.msg = 'Keeping voice websocket alive with timestamp %s.'

    def get_payload(self):
        return {
            'op': self.ws.HEARTBEAT,
            'd': int(time.time() * 1000)
        }

class DiscordWebSocket(websockets.client.WebSocketClientProtocol):
    """Implements a WebSocket for Discord's gateway v6.

    This is created through :func:`create_main_websocket`. Library
    users should never create this manually.

    Attributes
    -----------
    DISPATCH
        Receive only. Denotes an event to be sent to Discord, such as READY.
    HEARTBEAT
        When received tells Discord to keep the connection alive.
        When sent asks if your connection is currently alive.
    IDENTIFY
        Send only. Starts a new session.
    PRESENCE
        Send only. Updates your presence.
github hsahovic / poke-env / src / poke_env / player / player_network_interface.py View on Github external
:param server_configuration: Server configuration.
        :type server_configuration: ServerConfiguration
        :param start_listening: Wheter to start listening to the server. Defaults to
            True.
        :type start_listening: bool
        """
        self._authentication_url = server_configuration.authentication_url
        self._avatar = avatar
        self._password = player_configuration.password
        self._username = player_configuration.username
        self._server_url = server_configuration.server_url

        self._logged_in: Event = Event()
        self._sending_lock = Lock()

        self._websocket: websockets.client.WebSocketClientProtocol  # pyre-ignore
        self._logger: Logger = self._create_player_logger(log_level)  # pyre-ignore

        if start_listening:
            self._listening_coroutine = ensure_future(self.listen())