简体   繁体   中英

Python websockets send ping frame

Unless I'm mistaken, this isn't a SO duplicate. I'm not using Tornado, I just want to send a ping frame every 30s to keep the connection alive using the websockets library.

Being a risk taker, I had a guess but I don't know what to make of the server reply:

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>

(I already have an established connection to produce the 'Future pending' response.)

If client and server both use the same library, the PING and PONG frame not send automatically, when one side want to check if another side is still online, it send a PING frame by calling the ping() method from user, another side auto reply the PING frame by call the pong() method internally, so we don't need to take care about incoming PING frame and call pong() by our self. (Think of pong() as a private function.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM