Home » Python

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 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 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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.