我有一个使用Unix Socket的Ruby服务器:
require 'socket'
require 'json'
server = UNIXServer.new('/tmp/ciccio.sock')
loop do
sock = server.accept
loop do
begin
data = sock.recv(1024)
break if data.empty?
# calculate a response
response = {supermega: "very long json" * 10000}
sock.write(response.to_json)
sock.flush
rescue Errno::EPIPE, Errno::ENOTCONN
break
end
end
end
我在JavaScript中使用node.js net api:
Net = require('net');
var client = Net.connect({ path: '/tmp/ciccio.sock' }, () => {
console.log('write data');
client.write('hello world!');
});
client.on('data', (data) => {
console.log(data.toString());
var json = JSON.parse(data);
// do something with json
});
client.on('end', () => {
console.log('end');
});
client.on('error', (error) => {
console.log(error.toString());
});
问题是如果数据很大(大约8193个字符)JSON.parse
失败,因为data
被分块。如何将整个json作为字符串然后解析呢?
答案 0 :(得分:0)
您应该只在收到所有文本后解析JSON。在客户端试试这个。
Net = require('net');
var client = Net.connect({ path: '/tmp/ciccio.sock' }, () => {
console.log('write data');
client.write('hello world!');
});
// this will contain the whole JSON String
var totalString = '';
client.on('data', (data) => {
// progressively add the chunks to totalString
var chunk = data.toString();
console.log(chunk);
totalString += chunk;
});
client.on('end', () => {
// now you may parse the JSON
var json = JSON.parse(totalString);
totalString = ''; // release totalString to the garbage collector
// now do something with json
console.log('end');
});
client.on('error', (error) => {
console.log(error.toString());
});
注意 如果您有某种方法可以预测数据的大小,那么这可以更有效地完成。附加+=
的字符串效率非常低。