that these two calls write 20 bytes from an array BufA1 and 30 bytes from an array BufA2 to the socket,
and those bytes will be sent to machine B.
From TCP's point of view this is just a set of 50 bytes-not two sets of bytes, one of 20 and the other of 30.
There will be no "fence", no "dotted line," etc. delineating some kind of boundary between the two sets of
bytes. Moreover, on the receiver end at machine B, with a read() inside a while loop, we may, for instance,
receive first 15 bytes, then 25, then 10. (However, the call to read() will not return until at least one byte is
read, unless the socket is nonblocking, to be discussed later.) In that second chunk of 25 bytes, the first 5
of them would in this example be from the first call to write() on the sender end, with the other 5 from the
second call, but again there will be no demarcation between these two sets of 5.
On the receiver end, we can keep reading until read() returns a nonpositive value; this indicates that the
sender has closed the socket, either by calling close() or by simply exiting the program. (Just as exiting a
program automatically closes all files, it also closes all sockets.) We would do this by, say, code like
char Buf[BUFSIZE],*Ptr;
...
Ptr = Buf;
do {
NBytesRead = read(SD,Ptr,BUFSIZE);
TotMsgSize += NBytesRead;
Ptr += NBytesRead;
} while (NBytesRead > 0);
So, even a single call to write() at the sender will need a loop containing read() on the receiver end, rather
than just a single call to read().11
By contrast, in UDP one call to write() at the sender does need to be matched by only one call to read()
by the receiver. As opposed to TCP, in which the totality of bytes sent by the sender is just considered to be
one long stream, the bytes sent by separate calls to write() are considered to be separate from each other.
The set of bytes sent by a single call to write() is called a datagram.12
So, the application programmer must make a decision. If TCP is used, the programmer must add his/her
own code to separate the various messages within the stream. Things would thus be easier under UDP,
11 On the sending end, it is conceivable that even a call to write() may not send as many bytes as requested, if the OS kernel's
write buffer is nearly full. However, the best reference on TCP/IP programming (UNIX Network Programming, by Richard Stevens,
pub. Prentice-Hall, vol. 1, 2nd ed., p.77) says that this "is normally seen with write() only if the socket is nonblocking."
12Not to be confused with the same term for a packet at the IP level.
10
since there messages are received in the same sizes as they are sent. But on the other hand, with UDP the
programmer would have to add his/her own code for "chunking," error checking, etc. (if needed).
Note that TCP has a slow startup time, due to the handshaking between the two nodes as the connection
Overview of Computer Networks
Start from the beginning
