1
votes

can i detect ( if yes how?) when my Python3.6 Sanic Web Server lost connection with client application (example: user closes web browser or network fails, etc...)


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)

1

1 Answers

5
votes

Solved

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)