亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python websocket onclose

Python websocket onclose

慕桂英4014372 2023-07-05 15:34:31
WebSocket.onclose()在 javascript 中,當服務器關閉 websocket 連接時,我們必須做一些事情。當客戶端設備關閉連接時,有沒有辦法在 Python 服務器中執行相同的操作?服務器是使用websockets模塊本身使用該websockets.serve()方法來運行的。.Connected&都不.ConnectionClosed是屬性WebSocketServerProtocol(或者錯誤是這樣說的)。任何幫助,將不勝感激。
查看完整描述

1 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

recv() 和 send() 都會在關閉的連接上引發 websockets.exceptions.ConnectionClosed 。在那里進行清理工作。

以下是對文檔中的 websocket Web 示例的輕微修改:

import asyncio

import datetime

import random

import websockets


async def time(websocket, path):

? ? while True:

? ? ? ? now = datetime.datetime.utcnow().isoformat() + "Z"

? ? ? ? try:

? ? ? ? ? ? await websocket.send(now)

? ? ? ? except websockets.exceptions.ConnectionClosed:

? ? ? ? ? ? print("Client disconnected.? Do cleanup")

? ? ? ? ? ? break? ? ? ? ? ? ?

? ? ? ? await asyncio.sleep(random.random() * 3)


start_server = websockets.serve(time, "127.0.0.1", 5678)


asyncio.get_event_loop().run_until_complete(start_server)

asyncio.get_event_loop().run_forever()

客戶端示例:


import asyncio

import websockets


async def hello():

? ? uri = "ws://localhost:5678"

? ? count = 5

? ? async with websockets.connect(uri) as websocket:

? ? ? ? while count > 0:

? ? ? ? ? ? greeting = await websocket.recv()

? ? ? ? ? ? print(f"< {greeting}")

? ? ? ? ? ? count = count - 1


asyncio.get_event_loop().run_until_complete(hello())


查看完整回答
反對 回復 2023-07-05
  • 1 回答
  • 0 關注
  • 234 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號