How to have Sanic respond with http and ws?

做~自己de王妃 提交于 2019-12-01 12:24:58

Using 0.0.0.0 as your endpoint within your client html doesn't make any sense and you're not using SSL so you want to use ws:// rather than wss://. In other words,

from sanic import Sanic
from sanic import response
from sanic.websocket import WebSocketProtocol

app = Sanic()

@app.websocket('/feed')
async def feed(request, ws):
    while True:
        data = 'hello!'
        print('Sending: ' + data)
        await ws.send(data)
        data = await ws.recv()
        print('Received: ' + data)

@app.route('/html2')
async def handle_request(request):
  return response.html("""<html><head><script>
         var exampleSocket = new WebSocket("ws://" + location.host + '/feed');
         exampleSocket.onmessage = function (event) {
         console.log(event.data)};</script></head><body><h1>Hello socket!</h1><p>hello</p></body></html>""")

app.run(host="0.0.0.0", port=8000)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!