Nodejs streaming

后端 未结 2 1094
你的背包
你的背包 2021-02-19 10:46

I want to realize a simple client-server connection using Nodejs. But I\'ve encountered with the following problem.

Consider the code

server.js:

         


        
相关标签:
2条回答
  • 2021-02-19 11:39

    TCP is a stream protocol. Single write on one end of the pipe can result in multiple "reads" on the other end, and the other way around. You have to either explicitly tell the other side how many bytes you are sending by including the length in the message; or provide easily recognizable message delimiters. In any case you need to read in a loop.

    0 讨论(0)
  • 2021-02-19 11:48

    use socket.write return value and callback as documented here https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback to know when the data is completly flushed to the kernel . Wait for that to happen and after that call the second write. that way you make sure of the ordering. Regarding the problem of logic separartion of "a" and "b" you might want to design/implement that "protocol yourself, it's not a responsiblity of the (low-level) socket API.

    0 讨论(0)
提交回复
热议问题