从Node.js中的TCP套接字读取字符串时出现问题 [英] Issues when reading a string from TCP socket in Node.js
问题描述
我已经实现了使用TCP套接字进行通信的客户端/服务器.我要写入套接字的数据是字符串化的JSON.最初,一切都按预期工作,但是,随着我提高写入速度,我最终遇到JSON解析错误,其中客户端的开头在旧的结尾接收了新的写入的开头.
I've implemented a client/server that communicate using a TCP socket. The data that I'm writing to the socket is stringified JSON. Initially everything works as expected, however, as I increase the rate of writes I eventually encounter JSON parse errors where the beginning on the client receives the beginning of the new write on the end of the old one.
这是服务器代码:
var data = {};
data.type = 'req';
data.id = 1;
data.size = 2;
var string = JSON.stringify(data);
client.write(string, callback());
这是我在客户端服务器上接收此代码的方式:
Here is how I am receiving this code on the client server:
client.on('data', function(req) {
var data = req.toString();
try {
json = JSON.parse(data);
} catch (err) {
console.log("JSON parse error:" + err);
}
});
随着费率增加,我收到的错误是:
The error that I'm receiving as the rate increases is:
SyntaxError: Unexpected token {
这似乎是下一个被标记为当前请求末尾的请求的开始.
Which appears to be the beginning of the next request being tagged onto the end of the current one.
我尝试使用;作为每个JSON请求末尾的分隔符,然后使用:
I've tried using ; as a delimiter on the end of each JSON request and then using:
var data = req.toString().substring(0,req.toString().indexOf(';'));
但是,这种方法并没有导致JSON解析错误,而是随着我将每秒写入速度提高了300次,似乎导致客户端完全丢失了一些请求.
However this approach, instead of resulting in JSON parse errors seems to result in completely missing some requests on the client side as I increase the rate of writes over 300 per second.
是否有最佳实践或更有效的方法来限制通过TCP套接字的传入请求?
Are there any best practices or more efficient ways to delimit incoming requests via TCP sockets?
谢谢!
推荐答案
感谢大家的解释,他们帮助我更好地理解了通过TCP套接字发送和接收数据的方式.下面是我最后使用的代码的简要概述:
Thanks everyone for the explanations, they helped me to better understand the way in which data is sent and received via TCP sockets. Below is a brief overview of the code that I used in the end:
var chunk = "";
client.on('data', function(data) {
chunk += data.toString(); // Add string on the end of the variable 'chunk'
d_index = chunk.indexOf(';'); // Find the delimiter
// While loop to keep going until no delimiter can be found
while (d_index > -1) {
try {
string = chunk.substring(0,d_index); // Create string up until the delimiter
json = JSON.parse(string); // Parse the current string
process(json); // Function that does something with the current chunk of valid json.
}
chunk = chunk.substring(d_index+1); // Cuts off the processed chunk
d_index = chunk.indexOf(';'); // Find the new delimiter
}
});
欢迎评论...
这篇关于从Node.js中的TCP套接字读取字符串时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!