Python websockets发送ping fram

2024-09-30 12:20:26 发布

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

除非我弄错了,否则这不是一个很重复的东西。我不是使用Tornado,我只想每隔30秒发送一个ping帧,以使用websockets库保持连接。在

作为一个冒险者,我有一个猜测,但我不知道如何理解服务器回复:

import websockets
import asyncio

async def test_ping():
    websocket = await websockets.connect('wss://api.example.com')
    reply = await websocket.ping()
    print(reply)

loop = asyncio.new_event_loop()
loop.create_task(test_ping())
loop.run_forever()

>> <Future pending>

(我已经建立了一个连接以生成“未来待定”响应。)


Tags: testimport服务器loopasyncioasyncwebsocketsdef
1条回答
网友
1楼 · 发布于 2024-09-30 12:20:26

如果客户机和服务器都使用同一个库,PING和PONG帧不会自动发送,当一方要检查另一方是否在线时,它通过调用用户的PING()方法发送PING帧,另一方通过内部调用PONG()方法自动回复PING帧,所以我们不需要关心传入的PING我们自己帧并调用pong()。(可以将pong()看作一个私有函数。)

def read_data_frame(self, max_size):
    """
    Read a single data frame from the connection.

    Process control frames received before the next data frame.

    Return ``None`` if a close frame is encountered before any data frame.

    """
    # 6.2. Receiving Data
    while True:
        frame = yield from self.read_frame(max_size)

        # 5.5. Control Frames
        if frame.opcode == OP_CLOSE:
            # 7.1.5.  The WebSocket Connection Close Code
            # 7.1.6.  The WebSocket Connection Close Reason
            self.close_code, self.close_reason = parse_close(frame.data)
            # Echo the original data instead of re-serializing it with
            # serialize_close() because that fails when the close frame is
            # empty and parse_close() synthetizes a 1005 close code.
            yield from self.write_close_frame(frame.data)
            return

        elif frame.opcode == OP_PING:
            # Answer pings.
            # Replace by frame.data.hex() when dropping Python < 3.5.
            ping_hex = binascii.hexlify(frame.data).decode() or '[empty]'
            logger.debug("%s - received ping, sending pong: %s",
                         self.side, ping_hex)
            yield from self.pong(frame.data)

        elif frame.opcode == OP_PONG:
            ...

{a1}

相关问题 更多 >

    热门问题