Websocket keep alive in Python

Python Websocket keep alive: Here, we are going to learn how to send Websocket keep alive in Python? Submitted by Sapna Deraje Radhakrishna, on October 12, 2019

Websockets

Websockets uses HTTP as the initial transport mechanism but keeps the TCP connection alive after the HTTP response is received so that it can be used for sending messages between the client and server. The advantage of using web-sockets, allows us to bind "real-time" applications using the long-polling.

Keeping the WebSocket connection between client and server

Keeping the WebSocket connection between client and server helps in having a stream of information being flowed without any distraction. However, due to exceptions, the connectivity between the server and the client could be disrupted. The below examples demonstrate a few of the possible ways to keep the connection between the server and client alive.

Few options to keep the Websocket connection alive from client side is

Send a heart-beat or ping

In order to keep the session alive, the client could keep sending a heart-beat or a ping to the server.

@asyncio.coroutine
def _start_loop(self, websocket, event_handler):
    while True:
    	try:
    		yield from asyncio.wait_for(
    		self._wait_for_message(websocket, event_handler),
    		timeout=self.options['timeout']
    		)
    	except asyncio.TimeoutError:
    		yield from websocket.pong()
    		log.debug("Sending heartbeat...")
    		continue

Use the retry decorator: https://pypi.org/project/retry/

The retry decorator, every time there is WebSocketConnectionClosedException, reconnects to the WebSocket server in a delay of 2 seconds, keeping the session alive.

The delay is a configurable value that could be varied based on the requirement.

@retry(websocket.WebSocketConnectionClosedException, delay=2, logger=None)
def start_wss_client():
    '''
        Summary:
            This method initiates the wss connectivity
    '''
    wss_gateway_host = "ws://{0}:{1}".format(wss_gateway_host, wss_gateway_port)
    web_socket = websocket.WebSocketApp(wss_gateway_host,
                                        on_message=on_message,
                                        on_error=on_error,
                                        on_close=on_close)
    web_socket.on_open = on_open
    web_socket.run_forever()

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.