1

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

从 sanic 进口 Sanic
导入 sanic.response 作为响应

应用程序 = Sanic()


@app.route('/')
异步定义索引(请求):
    返回等待 response.file('index.html')


@app.websocket('/wsgate')
async def feed(request, ws):
    而真:
        数据 = 等待 ws.recv()
        print('收到:' + 数据)
        res = doSomethingWithRecvdData(数据)
        等待 ws.send(res)



如果 __name__ == '__main__':
    app.run(主机=“0.0.0.0”,端口=8000,调试=真)

4

1 回答 1

5

解决了

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)
于 2017-08-03T17:30:00.070 回答