【发布时间】:2018-02-01 16:52:22
【问题描述】:
我正在尝试确定我的实时服务器上的 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 变量清除。
用户表示,一种可能性是通过字节大小捕获数据。不幸的是,我无法使用此选项,因为我不知道我的流会有多大。
我已经使用; 来捕获数据的端点,这就是我所知道的。
【问题讨论】:
标签: javascript node.js sockets tcp