首页 > 解决方案 > 在处理数据时如何保持 websocket 处于活动状态?

问题描述

我正在连接一个 websocket 服务器并从中请求数据,我面临的问题如下:

  1. websocket 服务器每 10 秒向我发送一条消息,我必须在收到该消息后立即回复。

  2. 当我处理从服务器接收到的数据时,我需要超过 10 秒,假设我需要大约 5 分钟来处理接收到的每个数据。

  3. 我有一个循环,循环执行:首先从 websocket 连接接收数据,然后在本地计算机中处理(这需要时间),发送另一个请求并从 websocket 连接接收新数据等等。

我想保持 websocket 连接处于活动状态,但是我需要回复服务器的时间间隔大约是 10 秒,这比我需要处理数据的时间短得多,我该怎么办?

以下伪代码解释了上述语句:

import websocket 
import time

ws = websocket.WebSocket() 
ws.connect("wss://example.com")


def keep_alive():
    # this is what I need to interact to keep the connection on
    while True:
        data_recvd = ws.recv()  # suppose the received data is always an integer
        if data_recvd > 1000:
            ws.send(data_recvd)


def process_data(data):
    # suppose the processing takes very long time
    print(data)
    time.sleep(300)
    pass


for i in range(100):
    ws.send("message %d" % i)
    data = ws.recv()
    if data < 1000:
        process_data(data)  # if I write the program like this, the connection will be lost.

标签: python-3.xmultithreadingwebsocket

解决方案


我认为你的伪代码比它应该的要复杂一些。我将使用 JavaScript 编写解决此问题的版本(并且您必须指定端口)。

const ws = new WebSocket("wss://example.com:80");
ws.onMessage = function(event){
   ws.send("Hello, server");
   executeAsync(longFunction());       
}
function longFunction(){
//timeout 5 min
}

您需要做的就是创建一个新线程(异步运行长函数)。当 longFunction 完成后,线程关闭并返回无限循环(在我的代码片段中,ws.onMessage 无限监听服务器消息)。但是一段时间后,您将拥有与服务器发送消息一样多的线程,因此,创建线程时要小心。


推荐阅读