javascript - NodeJS 缓冲不完整的 TCP 流数据

标签 javascript node.js sockets tcp

我正在尝试确定我的实时服务器上的 TCP JSON 流的问题。我发现,如果通过 TCP(JSON 格式)流式传输给我的数据太大,那么它就不会始终如一地进行解析。我必须流式传输几次才能成功。

我使用的代码如下:

socket.once('data', function(data){
    let chunk = "";
    chunk += data.toString(); // Add string on the end of the variable 'chunk'
    let d_index = chunk.indexOf(';'); // Find the delimiter
    // While loop to keep going until no delimiter can be found
    while (d_index > -1) {         
        try {
            let string = chunk.substring(0,d_index); // Create string up until the delimiter
            let json = JSON.parse(string); // Parse the current string
            pages.addJSON(string);
            console.log(json.pagename); // Function that does something with the current chunk of valid json.    

        }
        catch(e){
            console.log(e);
        }
        chunk = chunk.substring(d_index+1); // Cuts off the processed chunk
        d_index = chunk.indexOf(';'); // Find the new delimiter
    }      
});

我的数据以 JSON 文件的形式流式传输给我,使用 ; 分隔每个流。例如,{"page": "something"};

我正在使用来自 this question 的代码并且其中一个响应警告我们应该缓冲任何不完整的代码。我想知道如何去做,因为我相信我的问题可能源于这个问题。

由于我的 JSON 流有些大,我认为很多数据没有通过连接传递,然后被我的 chunk 变量清除。

用户表示,一种可能性是通过字节大小来捕获数据。不幸的是,这个选项对我不可用,因为我不知道我的流会有多大。

我已经使用 ; 来捕获数据的端点,这就是我所知道的。

最佳答案

socket.once('data', ...) 可能会给您带来问题,因为 .once()。如果您没有在第一个 data 事件中获取所有数据,您将永远看不到其余数据。对于给定数据事件有多少数据,根本无法保证。它可能会因一系列因素而异。在慢速链接或与某处代理的链接上,您可能会在多个数据事件中获得较小的数据片段,如果数据很大,您几乎可以保证获得多个数据事件,因为它会在某处填满缓冲区。

您需要使用 socket.on('data', ...) 以便您可以看到此事务中的所有 data 事件,然后,如果您需要完成后删除事件处理程序,然后可以在阅读完所有内容并完成后将其删除。

另外,请注意您从 that other question 借用的代码使用 socket.on(),而不是 socket.once()


您还需要将 chunk 变量的定义移到事件处理程序之外,以便它从一个事件到下一个事件仍然存在。

let chunk = "";
socket.once('data', function(data){
    chunk += data.toString(); // Add string on the end of the variable 'chunk'
    let d_index = chunk.indexOf(';'); // Find the delimiter
    ....

关于javascript - NodeJS 缓冲不完整的 TCP 流数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48556814/

相关文章:

javascript - 如何使用 JavaScript 更新或添加数组中的值?

javascript - 我无法在主机上启动 node.js

java - "Software caused connection abort: recv failed"的原因

javascript - 计算字符串中特定字符的数量

javascript - IntelliSense JavaScript 引用的最佳实践

javascript - Javascript 中如何检查是否只有一个值不为空?

node.js - Keystone 无法隐藏 x-powered-by

node.js - AWS Lambda函数流程

python - Python套接字connect()与connect_ex()

sockets - Wireshark 和数据长度