views:

58

answers:

1

What's the difference between a "stream-type" socket and a "datagram" socket type?

+5  A: 

The short answer: message boundaries and connections.

With a stream socket you can write two five byte messages and wind up reading one ten byte message. This is because the data you write just gets placed into a single stream, with no boundaries between data written. This is just like writing a word at a time to a file. As a reader of the file, how do you know whether the writer originally wrote to the file one character at a time, one word at a time, one sentence at a time, one paragraph at a time or wrote the whole file all at once? Basically, if the file is already written, you don't. With a stream, how will you know that the source sent two five byte messages or one ten byte message if the sending was done in rapid succession? You have to have some sort of length or delimiter to help indicate message boundaries. Sometimes you don't care about messages or their boundaries. Other times, you add application level data (e.g., headers, delimiters, pre-defined message lengths, etc...). This makes a stream socket usable as well, since you handle the messaging yourself (i.e., at the application layer).

With a datagram based socket, the receiver knows the size of the messages that the sender sent, because they are delivered 1:1 (baring losses, dups, etc...), retaining their original sizes.

In addition to all of this, stream based sockets tend to be connection oriented and 1:1, while datagram sockets connectionless and potentially one (source) to many (receivers), with broadcast / multicast.

Michael Goldshteyn