qnilab
qnilab

Reputation: 474

Multiplex connection over a single TCP socket

Let's assume I have two machines, A and B, which run two programs each:

A TCP socket (duplex) connects A to B.

Upon reception of a message from A, B needs to know where to dispatch the message: should it go to B.1, or B.2 ? And vice versa.

A naive idea could be to prefix each message with a kind of header identifying the program to map to. Instead of sending "message to B.1", A could send "1: message to B.1". Upon reception, B sees the header "1: ", and knows to send "message to B.1" to B.1.

The problem is that messages can be split and when A sends "1: message to B.1", B could very well receive several chunks:

If the chunks all have the same length, I can split the original messages in small chunks, each prefixed with a header. That adds some overhead, but that's fine.

The problem is: I am not sure I can configure the chunk size. Chunks may be of random lengths. If both A.1 and A.2 write to B.1 and B.2 respectively, I am not sure how B can know how to properly dispatch the chunks to the right recipients.

I'm using nodejs by the way. I'll look into the readableHighWaterMark and writableHighWaterMark options of the Duplex module to see if I can fix the chunk size, but I'm not sure this is how it works.

Any tips / ideas?

Upvotes: 0

Views: 309

Answers (1)

Yuri Myakotin
Yuri Myakotin

Reputation: 61

Header should be fixed size and contain both target program id and current chunk data size. On receiving size - read fixed size header, then read exactly nnn bytes of data as specified in header (you have to call read/recv repeatly until entire chunk received) and dispatch that data to corresponging program. Then read next header etc etc etc

Upvotes: 0

Related Questions