WebSockets Client¶
New in version 0.15.
aiohttp
works with client websockets out-of-the-box.
You have to use the ws_connect()
coroutine 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
If you prefer to establish websocket client connection from
ClientSession
object please use
aiohttp.client.ClientSession.ws_connect()
coroutine:
session = aiohttp.ClientSession()
ws = yield from session.ws_connect(
'http://webscoket-server.org/endpoint')
You must use the only websocket task for both reading (e.g yield
from ws.receive()
) and writing but may have multiple writer tasks
which can only send data asynchronously (by yield from
ws.send_str('data')
for example).
ClientWebSocketResponse¶
To connect to a websocket server you have to use the aiohttp.ws_connect() function,
do not create an instance of class ClientWebSocketResponse
manually.
-
coroutine
aiohttp.websocket_client.
ws_connect
(url, *, protocols=(), timeout=10.0, connector=None, ws_response_class=ClientWebSocketResponse, autoclose=True, autoping=True, loop=None)[source]¶ This function creates a websocket connection, checks the response and returns a
ClientWebSocketResponse
object. In case of failure it may raise aWSServerHandshakeError
exception.Parameters: - url (str) – Websocket server url
- protocols (tuple) – Websocket protocols
- timeout (float) – Timeout for websocket read. 10 seconds by default
- connector (obj) – object
TCPConnector
- ws_response_class –
WebSocketResponse class implementation.
ClientWebSocketResponse
by default.New in version 0.16.
- autoclose (bool) – Automatically close websocket connection on close message from server. If autoclose is False them close procedure has to be handled manually
- autoping (bool) – Automatically send pong on ping message from server
- loop –
event loop used for processing HTTP requests.
If param is
None
asyncio.get_event_loop()
used for getting default event loop, but we strongly recommend to use explicit loops everywhere.
-
class
aiohttp.websocket_client.
ClientWebSocketResponse
[source]¶ Class for handling client-side websockets.
-
closed
¶ Read-only property,
True
ifclose()
has been called ofMSG_CLOSE
message has been received from peer.
-
protocol
¶ Websocket subprotocol chosen after
start()
call.May be
None
if server and client protocols are not overlapping.
-
ping
(message=b'')[source]¶ Send
MSG_PING
to peer.Parameters: message – optional payload of ping message, str
(converted to UTF-8 encoded bytes) orbytes
.
-
send_str
(data)[source]¶ Send data to peer as
MSG_TEXT
message.Parameters: data (str) – data to send. Raises TypeError: if data is not str
-
send_bytes
(data)[source]¶ Send data to peer as
MSG_BINARY
message.Parameters: data – data to send. Raises TypeError: if data is not bytes
,bytearray
ormemoryview
.
-
coroutine
close
(*, code=1000, message=b'')[source]¶ 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:
-
coroutine
receive
()[source]¶ A coroutine that waits upcoming data message from peer and returns it.
The coroutine implicitly handles
MSG_PING
,MSG_PONG
andMSG_CLOSE
without returning the message.It process ping-pong game and performs closing handshake internally.
Returns: Message
, tp is types of ~aiohttp.MsgType
-