2017-08-03 37 views
1

我可以檢測到(如果是如何?)當我的Python3.6中信高科Web服務器失去了與客戶端應用程序的連接(例如:用戶關閉Web瀏覽器或網絡故障等)我可以在使用Python3.6 Sanic的websockets中檢測'連接丟失'嗎?

 

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) 

回答

2

解決

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)