我可以使用 Python3.6 Sanic 在 websockets 中检测 'connection lost' 吗?

Can i detect 'connection lost' in websockets using Python3.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.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)

已解决

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)