Python websockets发送ping帧

时间:2018-02-28 18:07:24

标签: python websocket ping

除非我弄错了,否则这不是SO副本。我使用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>

(我已经建立了连接以产生&#39; Future pending&#39;响应。)

1 个答案:

答案 0 :(得分:0)

如果客户端和服务器都使用相同的库,则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:
            ...

To see the full version of the read_data_frame function