我可以使用Python3.6 Sanic检测websockets中的“连接丢失”吗?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我可以使用Python3.6 Sanic检测websockets中的“连接丢失”吗?相关的知识,希望对你有一定的参考价值。
当我的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)
以上是关于我可以使用Python3.6 Sanic检测websockets中的“连接丢失”吗?的主要内容,如果未能解决你的问题,请参考以下文章