Websocket在Python中保持活力

Websockets使用HTTP作为初始传输机制,但收到HTTP响应后仍保持TCP连接有效,以便可用于在客户端和服务器之间发送消息。使用网络套接字的优势使我们可以使用长轮询来绑定“实时”应用程序。

保持客户端与服务器之间的WebSocket连接有助于使信息流畅通无阻。但是,由于异常,服务器和客户端之间的连接可能会中断。下面的示例演示了使服务器与客户端之间的连接保持活动状态的几种可能方法。

保持客户端Websocket连接保持活动状态的几种方法是

发送心跳或ping

为了使会话保持活动状态,客户端可以继续向服务器发送心跳或ping。

@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

使用重试装饰器:https://pypi.org/project/retry/

重试装饰器,每次出现WebSocketConnectionClosedException时,都会以2秒的延迟重新连接到WebSocket服务器,以保持会话处于活动状态。

延迟是一个可配置的值,可以根据要求进行更改。

@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()