New in version 0.15.
aiohttp works with client websockets out-of-the-box.
You have to use the aiohttp.ws_connect() function for client websocket connection. It accepts a url as a first parameter and returns ClientWebSocketResponse, with that object you can communicate with websocket server using response’s methods:
ws = yield from aiohttp.ws_connect('http://webscoket-server.org/endpoint')
while True:
msg = yield from ws.receive()
if msg.tp == aiohttp.MsgType.text:
if msg.data == 'close':
yield from ws.close()
break
else:
ws.send_str(data + '/answer')
elif msg.tp == aiohttp.MsgType.closed:
break
elif msg.tp == aiohttp.MsgType.error:
break
You can have the only websocket reader task (which can call yield from ws.receive()) and multiple writer tasks which can only send data asynchronously (by yield from ws.send_str('data') for example).
To connect to a websocket server you have to use the aiohttp.ws_connect() function, do not create an instance of class ClientWebSocketResponse manually.
This function creates a websocket connection, checks the response and returns a ClientWebSocketResponse object. In case of failure it may raise a WSServerHandshakeError exception.
Parameters: |
|
---|
Class for handling client-side websockets.
Read-only property, True if close() has been called of MSG_CLOSE message has been received from peer.
Websocket subprotocol chosen after start() call.
May be None if server and client protocols are not overlapping.
Send MSG_PING to peer.
Parameters: | message – optional payload of ping message, str (converted to UTF-8 encoded bytes) or bytes. |
---|
Send data to peer as MSG_TEXT message.
Parameters: | data (str) – data to send. |
---|---|
Raises TypeError: | |
if data is not str |
Send data to peer as MSG_BINARY message.
Parameters: | data – data to send. |
---|---|
Raises TypeError: | |
if data is not bytes, bytearray or memoryview. |
A coroutine that initiates closing handshake by sending MSG_CLOSE message. It waits for close response from server. It add timeout to close() call just wrap call with asyncio.wait() or asyncio.wait_for().
Parameters: |
---|
A coroutine that waits upcoming data message from peer and returns it.
The coroutine implicitly handles MSG_PING, MSG_PONG and MSG_CLOSE without returning the message.
It process ping-pong game and performs closing handshake internally.
Returns: | Message, tp is types of ~aiohttp.MsgType |
---|