gpt4 book ai didi

javascript - 如何在浏览器中显示大量的websocket消息?

转载 作者:行者123 更新时间:2023-12-02 23:13:38 24 4
gpt4 key购买 nike

我从事一个项目,正在构建一个 Web 应用程序,该应用程序从日志文件中读取任务并将数据作为 websocket 消息发送到浏览器。我使用 Django 作为服务器。当我想在浏览器中显示所有消息时遇到问题。由于大量消息,浏览器变得无响应。为了在浏览器中显示消息,我使用 .innerhtml

这是我的代码:

接受消息的函数:

    socket.onmessage = (e) => {
let consoleOutput = document.getElementById("console-output");
consoleOutput.innerHTML += e.data + "<br>";
console.log("message", e);
};

发送消息的函数:

    def websocket_receive(self, event):
response = json.loads(event["text"])
app_name = response.get("app_name")
path_to_logs_file = f"{pathlib.Path.home()}/logs/{app_name}/file.log"
process = subprocess.Popen(["tail", "-f", path_to_logs_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
start_time = datetime.datetime.now()
while True:
decoded_line = process.stdout.readline().decode("utf-8")
if decoded_line == '' and process.poll() is not None:
self.send({
"type": "websocket.close"
})
break
else:
self.send({
"type": "websocket.send",
"text": str(decoded_line).strip()
})

如何加快向元素追加数据的速度?我将不胜感激任何有用的建议。

最佳答案

查看您的问题,您似乎想使用 websockets 来显示日志。

一段时间后,不断地附加到innerHTML就会变得非常低效。

所以你可能想要做的是直接访问 DOM..

下面是一个示例,它仅显示当前时间(以毫秒为单位),并在一段时间后 trim 旧条目以防止内存增长。

const cd = document.querySelector("code");

setInterval(() => {
const txt = document.createTextNode(
`Current Time in ms: ${Date.now()}\n`);
cd.appendChild(txt);
if (cd.childNodes.length > 500) cd.childNodes[0].remove();
}, 10);
body {
background-color: black;
color: white;
}
code {
white-space: pre;
}
<code></code>

关于javascript - 如何在浏览器中显示大量的websocket消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com