0

In Socket programming, irrespective of whether you are writing code in C or java assume the following scenario.

Client has code similar to:

while(1) {
    read(...);
    /* process received msg */
    process(received_msg)
}

Now, the client received msg1 and is busy processing it. This means the processor is now running some instruction inside process(). At this point, msg2 arrives. But, there is no read() blocking now to receive it. What happens to the incoming message msg2 now?

Does it depend on the protocol? Does it depend on the language api?

I think if I make a new thread every time I receive a message I can overcome this issue. My question is aimed at understanding what happens in a single threaded context, and if there's any way to make this work without using multiple threads.

tomol
  • 755
  • 1
  • 6
  • 12
  • 2
    The kernel buffers the received data for you so that it is available on the next read. The kernel also manages what happens (protocol dependent) if it can't buffer anymore and other such conditions. – kaylum Oct 10 '16 at 01:28
  • If your message fits into the socket's buffer, you'll find it there. If the buffer becomes full, your TCP stack - (because sockets is streaming, thus TCP) - will inform the sender to hold those packets. See also on SO [what happens when I write data to a blocking socket, faster than the other side reads?](http://stackoverflow.com/questions/14241235/what-happens-when-i-write-data-to-a-blocking-socket-faster-than-the-other-side). – Adrian Colomitchi Oct 10 '16 at 01:29
  • "if there's any way to make this work without using multiple threads." - in a *single-thread synchronous processing* approach, if your processor is slower than the sender and you use TCP, you'll end by slowing the sender too. When multithreading wasn't available, UNIX-es used to fork/spawn another process for each request. – Adrian Colomitchi Oct 10 '16 at 01:37

1 Answers1

3

What happens to the incoming message msg2 now?

It is buffered.

Does it depend on the protocol?

I am describing TCP but the same is true of UDP. However the behaviour when the buffer fills is different for TCP and UDP: TCP stalls the sender; UDP drops the next datagrams.

Does it depend on the language api?

No.

I think if I make a new thread every time I receive a message I can overcome this issue.

There is no issue to overcome.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • >> There is no issue to overcome - there is one, actually. If receiver reads slower than sender sends, it may come that sender will face timeout and receiver will lose everything from latest received packet. It is better to have one thread that bufferize in heap rather than in OS's TCP buffer, and other thread to process it. Here developer will be able to decide on heap buffer size to meet task requirements. – iXCray Feb 25 '18 at 09:03