python-aiohttpHow to create a websocket server using Python Aiohttp?
Creating a websocket server using Python Aiohttp is easy and straightforward.
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:
await ws.send_str(msg.data + '/answer')
elif msg.type == web.WSMsgType.binary:
await ws.send_bytes(msg.data)
elif msg.type == web.WSMsgType.close:
break
return ws
app = web.Application()
app.add_routes([web.get('/', websocket_handler)])
web.run_app(app)
The code above creates a websocket server using Python Aiohttp. It creates a websocket handler which handles incoming websocket requests. It then adds a route to the application and runs the application.
The code consists of the following parts:
- Importing the necessary modules:
import asyncio
andfrom aiohttp import web
- Creating a websocket handler:
async def websocket_handler(request)
- Creating a websocket response:
ws = web.WebSocketResponse()
- Preparing the websocket response:
await ws.prepare(request)
- Handling incoming messages:
async for msg in ws
- Sending a response:
await ws.send_str(msg.data + '/answer')
- Creating an application:
app = web.Application()
- Adding a route to the application:
app.add_routes([web.get('/', websocket_handler)])
- Running the application:
web.run_app(app)
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to get response code with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to download large files with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to close a Python Aiohttp session?
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to set query parameters with Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to close a Python Aiohttp session?
See more codes...