Send byte array in node.js to server

前端 未结 2 1377
南方客
南方客 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/

    0 讨论(0)
  • 2021-02-13 20:54

    Buffer didn't work for me because I had a custom class named exactly as node.js's one. This works:

    testBuff = new Buffer([4, 0, -1, 1, 32, 0]);
    client.write(testBuff);
    
    0 讨论(0)
提交回复
热议问题