WebSocket

Sanic supports websockets, to setup a WebSocket:

  1. from sanic import Sanic
  2. from sanic.response import json
  3. from sanic.websocket import WebSocketProtocol
  4.  
  5. app = Sanic()
  6.  
  7. @app.websocket('/feed')
  8. async def feed(request, ws):
  9. while True:
  10. data = 'hello!'
  11. print('Sending: ' + data)
  12. await ws.send(data)
  13. data = await ws.recv()
  14. print('Received: ' + data)
  15.  
  16. if __name__ == "__main__":
  17. app.run(host="0.0.0.0", port=8000, protocol=WebSocketProtocol)

Alternatively, the app.add_websocket_route method can be used instead of the decorator:

  1. async def feed(request, ws):
  2. pass
  3.  
  4. app.add_websocket_route(feed, '/feed')

Handlers for a WebSocket route are passed the request as first argument, and a WebSocket protocol object as second argument. The protocol object has send and recv methods to send and receive data respectively.

You could setup your own WebSocket configuration through app.config, like

Find more in Configuration section.

Related Topics

本页

快速搜索