How do sockets send and read, through separate packets or will it concatenate them?

Let's say the client uses the send function twice to the server.

The server receives the packets, will it have to use read once or twice?

Client sends("Packet1")
Client sends("Packet2")

Server reads("Packet1")
Server reads("Packet2")


Server reads("Packet1Packet2")
The server receives the packets, will it have to use read once or twice?
Not necessarily. As a rule, you should read as much as you expect (repeatedly in a loop if necessary).
It also depends whether using TCP or UDP. UDP will have to read twice. TCP, it depends.

EDIT: For UDP, provided that you asked to read the number of bytes or max number of bytes you would expect your message should be.

Last edited on
For TCP, server may be able to read them both at the same time, assuming the buffer is big enough (Think about it like a network console).

UDP, as histrungalot said, will read them separately, assuming the messages reach the server.
Last edited on
TCP will split and join them up in unpredictable ways depending on the channel quality and how quick the sends are apart. Check out RFC-793 to understand why.

You have to re-assemble at the receiver, and decide where one packet starts and ends. Most often you will have to insert unique "start-of-packet" and "end-of_packet" markers in the stream to give the receiver a clue.

TCP/IP is a stream over a "connection", guaranteed to be error-free (or not at all) after all the retries have finished, while UDP/IP is just single packets that are dispatched (which can be lost or corrupted) but are adequate for a lot of tasks.

Wireshark and Ethereal are good teaching tools if you are playing around with networking.

Topic archived. No new replies allowed.