python-aiohttpHow to create a Python aiohttp websocket client?
Creating a Python aiohttp websocket client is relatively straightforward. The following example code creates a websocket client that connects to a websocket server and prints out any messages it receives:
import asyncio
from aiohttp import web
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
print('Received:', msg.data)
elif msg.type == web.WSMsgType.ERROR:
print('ws connection closed with exception %s' %
ws.exception())
print('websocket connection closed')
return ws
Output example
Received: Hello
Received: World
websocket connection closed
The code consists of the following parts:
import asyncio
andfrom aiohttp import web
: imports the necessary libraries for the websocket client.async def websocket_handler(request):
: defines the websocket handler function.ws = web.WebSocketResponse()
: creates a websocket response object.await ws.prepare(request)
: prepares the websocket response object.async for msg in ws:
: starts an asynchronous loop to receive messages from the websocket server.if msg.type == web.WSMsgType.TEXT:
: checks if the message type is text.if msg.data == 'close':
: checks if the message data is 'close'.await ws.close()
: closes the websocket connection.else:
: prints out the message data.elif msg.type == web.WSMsgType.ERROR:
: checks if the message type is an error.print('ws connection closed with exception %s' % ws.exception())
: prints out the exception.print('websocket connection closed')
: prints out a message when the websocket connection is closed.return ws
: returns the websocket response object.
Helpful links
Related
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to make parallel requests with Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to set query parameters with Python Aiohttp?
- How to use keepalive with Python Aiohttp?
See more codes...