help icon indicating copy to clipboard operation
help copied to clipboard

socket.write

Open hsocarras opened this issue 8 years ago • 11 comments

I'am using node v 6.7.0 on windows 7. The following example code works wrong. This is a fragment of on('connection') callback function for a tcp server.

socket.setNoDelay();
socket.on('data',function(data){
              var response = self.onData(data);               
               let writedStatus =  socket.write(response, 'utf8', function(){
                      if(self.onWrite){
                        self.onWrite(response);
                      }                      
                });
            
   });

When the server receive two request very fast from the same socket, it processed and call socket.write whit the response two times, but on client side only get one message with both response .

I need on client side:

[response 1]

[response 2]

I'm getting

[response1 response 2]

hsocarras avatar Feb 14 '18 17:02 hsocarras

The code fragment is not complete so I cannot say for sure what the logic server is following, but from your description, looks like the concern is about: server is sending data as soon as it can, setNoDelay is ON, but why the messages are coalesced.

Does this code represent your problem?

var net = require('net')
const server = net.createServer((s) => {
  s.setNoDelay(true)
  s.on('data', (d) => {
    s.write(d)
  })
})

server.listen(() => {
  const c = net.createConnection({ port: server.address().port}, () => {
    c.write('start')
  })
  c.setNoDelay(true)
  c.on('data', (d) => {
    console.log(`${d.toString()}`)
    c.write('hello')
    c.write(' world!')
  })
})

output:

hello world!
hello world!
hello world!
hello world!
hello
 world!hello world!
hello
 world!
hello world!hello world!
hello
 world!hello world!
hello world!

--trace data showed no buffering at the server side. tcpdump showed data being combined in the wire.

14:51:24.652894 IP localhost.55744 > localhost.55745: Flags [P.], seq 1:13, ack 7, win 65535, options [nop,nop,TS val 538171659 ecr 538171659], length 12
        0x0000:  4502 0040 9d26 4000 4006 0000 7f00 0001  E..@.&@.@.......
        0x0010:  7f00 0001 d9c0 d9c1 c339 081e 954e 2320  .........9...N#.
        0x0020:  8018 ffff fe34 0000 0101 080a 2013 d90b  .....4..........
        0x0030:  2013 d90b 6865 6c6c 6f20 776f 726c 6421  ....hello.world!

I guess whether setNoDelay is ON or OFF, data can be combined at the network layer. setNoDelay (Nagle algorithm off) eliminates the delay in sending packets to the destination, but does not guarentee distinct packaging of data that comes in chunks within very short intervals.

Hope this helps.

gireeshpunathil avatar Feb 22 '18 09:02 gireeshpunathil

Nagle's algorithm explicitly existed to control the overhead and congestion in the network caused by many packets with very small payloads (data size < packet header size). However, TCP also has further congestion control in the form of 'slow start', which may be another adaptive factor in controlling the rate at which unbuffered data is packetised and released onto the physical network by the sender.

That might explain why @gireeshpunathil's output starts consistently, but then compounds further in weird and wonderful ways.

shellberg avatar Feb 22 '18 13:02 shellberg

thanks @gireeshpunathil your code shows my problem. I need to avoid to messages are coalesced because is a undesirable behavior on my app. There are any way to avoid that?

hsocarras avatar Feb 22 '18 14:02 hsocarras

the root of the problem is that client sends multiple data without any care about their identity - in the example shown above, there is nothing like request response etc. , both endpoints are reading and writing to each other, in a duplex stream.

I don't know your real use case by which you need to write arbitrary sequence of data from the client without any differentiation but the server response needs to be discretely different.

There can be many ways to achieve this by controlling client or server or both, but one trivial but natural thing to do is to wait in the client for the response before sending the next request:

 server.listen(() => {
  const c = net.createConnection({ port: server.address().port}, () => {
    c.write('start')
  })
  c.setNoDelay(true)
  const buf = {true: 'hello', false: ' world!'}
  var pointer = true
  c.on('data', (d) => {
    console.log(`${d.toString()}`)
    c.write(buf[pointer])
    pointer = !pointer
  })
})
start
hello
 world!
hello
 world!
hello
 world!
hello
 world!
hello
 world!

Does it sound reasonable to you?

gireeshpunathil avatar Feb 22 '18 16:02 gireeshpunathil

That's the current implementation that i have. I'm writing a modbus library, currently the client send a request and have to wait for the server's response or timeout event to send another.

But according to modbus tcp specification the client must be able to send up to 16 request to the same server and the modbus message must be send only one in each tcp transaction.

hsocarras avatar Feb 22 '18 17:02 hsocarras

ok, thanks for sharing the use case. As you are not using any application level protocol and as the data can be coalesced in arbitrary manner in both the routes (c -> s and s -> c), we need a protocol definition at both sides to draw boundaries between requests and responses.

I will see how we can achieve this.

gireeshpunathil avatar Feb 23 '18 05:02 gireeshpunathil

@hsocarras - here is my attempt to address your use case. Please see if it helps you. As the client and server operates at TCP level, the data needs parsing at app level to 'decipher' request and response, and hence we need to resort to something like this. Few points:

  • Data needs to be delimited with a unique byte sequence that does not appear in the data itself. I have used *
  • error conditions needs to be covered.

gireeshpunathil avatar Mar 01 '18 08:03 gireeshpunathil

The modbus protocol are implemented by several vendors in they devices, and all must fulfill the modbus specification, because of that I'can't use any delimiters. Maybe this kind of device have no issues with messages coalesce.

hsocarras avatar Mar 01 '18 14:03 hsocarras

thanks @hsocarras. Is it that you don't have a control point for inserting a delimiter after each request, or is it that you cannot define a delimiter that will be a unique byte due to the plurality of vendor implementations?

the first one can be addressed, second one cannot.

In either way, this is a general programming problem and has nothing special with node.js.

Let me know if there is anything else on this, or else we can close this.

gireeshpunathil avatar Mar 02 '18 04:03 gireeshpunathil

I'm afraid it is the second. Thanks for your help.

hsocarras avatar Mar 03 '18 12:03 hsocarras

Closing, as there is nothing identified in node to be addressed.

gireeshpunathil avatar Mar 03 '18 13:03 gireeshpunathil