我可以使用Python3.6 Sanic检测WebSocket中的“连接丢失”吗?

我可以使用Python3.6 Sanic检测WebSocket中的“连接丢失”吗?,websocket,python-3.6,sanic,Websocket,Python 3.6,Sanic,我是否可以检测到是,如何检测?当我的Python3.6 Sanic Web服务器与客户端应用程序失去连接时,例如:用户关闭Web浏览器或网络故障等 from sanic import Sanic import sanic.response as response app = Sanic() @app.route('/') async def index(request): return await response.file('index.html') @app.websock

我是否可以检测到是,如何检测?当我的Python3.6 Sanic Web服务器与客户端应用程序失去连接时,例如:用户关闭Web浏览器或网络故障等

from sanic import Sanic import sanic.response as response app = Sanic() @app.route('/') async def index(request): return await response.file('index.html') @app.websocket('/wsgate') async def feed(request, ws): while True: data = await ws.recv() print('Received: ' + data) res = doSomethingWithRecvdData(data) await ws.send(res) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000, debug=True) 解决

解决


谢谢,这对我有用。奇怪的是,我发现当我在ws:中使用替代语法async for msg而不是显式调用recv时,它不会在断开连接时抛出异常。谢谢,这对我来说很有用。奇怪的是,我发现当我使用替代语法async for msg in ws:而不是显式调用recv时,它不会在断开连接时抛出异常。
from sanic import Sanic
import sanic.response as response
from websockets.exceptions import ConnectionClosed

app = Sanic()


@app.route('/')
async def index(request):
    return await response.file('index.html')


@app.websocket('/wsgate')
async def feed(request, ws):
    while True:
        try:
            data = await ws.recv()
        except (ConnectionClosed):
            print("Connection is Closed")
            data = None
            break
        print('Received: ' + data)
        res = doSomethingWithRecvdData(data)
        await ws.send(res)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8000, debug=True)