Send byte array in node.js to server

前端 未结 2 1378
南方客
南方客 2021-02-13 20:20

I can\'t figure out to send byte array while being connected to server on Debian. Is there any alternative to sending string via client.write()? I tried clien

2条回答
  •  终归单人心
    2021-02-13 20:44

    There's an example of a BufferStream class here, that can be used for turning buffers into readable streams.

    The article has an example of piping a buffer stream through a response object, however, seeing as client.connect returns a net.Socket which implements duplex Stream, you should equally be able to pipe the buffer stream into your client socket.

    For example:

    var buffer = new Buffer([0x4, 0xFF, 0x01, 0x20, 0x0]),
        stream = new BufferStream(buffer),
        client = net.connect({ host: 'someIp.pl', port: 7171 }, connected);
    
    function connected() {
      stream.pipe(client);
      // do other things
    }
    

    Generally speaking, if you can stream something in Node, you probably should. It's a more elegant model and allows you to do some cool things.

    There are a bunch of examples of streams in practice which are interesting to look at, here: http://nodestreams.com/

提交回复
热议问题