Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

javascript - Nodejs loopback TCP latency 1-2ms?

When creating a TCP server/client connected through the loopback address in NodeJS, I'm getting 1-2 ms round trip times for simple, low-data messages.

I don't have too much context for how fast Node should be, but it seems that it should be <1ms as there aren't very many operations going on and loopback ping times are in the microseconds.

Is there some buffering built into the net package that I'm missing, or is this latency to be expected?

Server:

var net = require('net');

var server = net.createServer((socket) => {
  socket.setNoDelay();

  setInterval(()=>{
    socket.write(process.hrtime.bigint().toString());
  }, 1000)



  socket.on('data', (data)=>{
    console.log("Completed in: " + parseFloat((process.hrtime.bigint() - BigInt(data))/BigInt(1e3))/1000 + "ms")
  })

});

server.listen(1337, '127.0.0.1');

Client:

var net = require('net');

var client = new net.Socket();
client.connect(1337, '127.0.0.1', () => {
    console.log('Connected');

});

client.on('data', (data) => {
    client.write(data.toString());
});

client.on('close', () => {
    console.log('Connection closed');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is expected behavior. I'm sure there's ways to optimize the interpreter, but if your use case needs real time response times (<1ms) maybe you should change your tech stack to some other language that can use cpu, multithreading, io, etc more efficiently.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...