关闭从js到python的websocket连接需要很多时间

2024-10-05 10:00:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现将字符串发送到js客户端的python websocket。 此websocket由客户端打开,由客户端关闭,但当我关闭连接时,websocket将继续发送数据一分钟。 为什么?

python服务器代码:

    Run = False

async def wsjson(websocket, path):

    data = datetime.datetime.now()

    sensors_data = []

    try:
        global Run
        while Run:               
                time.sleep(4)                         
                randomNumb = random.randint(1, 101)

                print(randomNumb)               
                await websocket.send(randomNumb)

    except websockets.ConnectionClosed:
        print("closed")     
        Run = False

start_server = websockets.serve(wsjson, '127.0.0.1', 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

这是js客户端代码:


function aproConn() {
    ws = new WebSocket("ws://127.0.0.1:5678/");
}

function chiudoConn() {
    ws.close();

    ws.onclose = function(event) { 
        console.log("I have closed conn") //1 more minute to show this
      };

}

Tags: run代码eventfalse客户端datadatetimews

热门问题