简体   繁体   English

如何将一系列数据包写入Node.js net.Socket?

[英]how to write a sequence of packets to a Node.js net.Socket?

Would like to know if there's anything special i need to do to write an array of packets, sequentially to an instance of net.Socket in Node.js. 想知道是否需要做一些特殊的事情来依次向Node.js中的net.Socket实例写入数据包数组。

I'm not sure if writing to the same socket in a for loop would be synchronous or also async. 我不确定在for循环中写入同一套接字是同步还是异步。

If it's async, would i have to promisify Socket.write and have the loop set up a .then() chain. 如果它是异步的,我是否必须对Socket.write进行Socket.write并让循环设置一个.then()链。 I'm already using bluebird for promises. 我已经在使用bluebird了。

thanks! 谢谢!

I was also confused by this. 我对此也感到困惑。 Most Node.js examples make it seem like write() is synchronous: 大多数Node.js示例都使write()看起来像是同步的:

var server = net.createServer(function(socket) {
  socket.write('Hello!');
  socket.end();
});

It turns out the non-callback version of write() actually means write_eventually() . 事实证明, write()的非回调版本实际上意味着write_eventually() If it can't actually write your data to the socket, it queues it up in memory. 如果它实际上无法将数据写入套接字,则会将其在内存中排队。 Node takes care of writing the queued data out to the socket eventually. Node负责最终将排队的数据写出到套接字。

I imagine they did this because callbacks are annoying and this reduces the number of callbacks in your code. 我想他们这样做是因为回调很烦人,这减少了代码中的回调次数。 The downside is that it uses more memory (see: Socket.bufferSize ). 缺点是它使用更多的内存(请参阅: Socket.bufferSize )。

If you're pushing lots of data, it's more memory-efficient to use the callback version of write() : 如果要推送大量数据,则使用write()的回调版本会更节省内存:

"use strict";

var net = require("net")

function writeArray(arrayOfChunks, socket, callback) {
  var i = 0;
  function f() {
    if (i >= arrayOfChunks.length) {
      callback();
    } else {
      socket.write(arrayOfChunks[i++], null, f);
    }
  }
  f()
}

var server = net.createServer((socket) => {
  var arrayOfChunks = ['Hello', ', ', 'world!', '\n'];
  writeArray(arrayOfChunks, socket, () => {
    socket.write('DONE\n', null, () => {
      socket.end();
    })
  })
})

server.listen(9191, () => {
  console.log("Server listening.");
})

But it's 2016, so maybe you can just use async / await and not have to deal with callback/promise nonsense. 但是现在是2016年,因此也许您可以只使用async / await ,而不必处理回调/承诺废话。

Multiple writes are guaranteed to be executed in order. 确保多次写入将按顺序执行。

Requests:Responses are not guaranteed to be mapped 1:1. 请求:不能保证将响应映射为1:1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM