Datagrams
Datagrams are similar to mailslots and are used in similar circumstances. There is no connection between the sender and receiver, and there can be multiple receivers. Delivery to the receiver is not ensured with either mailslots or datagrams, and successive messages will not necessarily be received in the order they were sent.The first step in using datagrams is to specify SOCK_DGRAM in the type field when creating the socket with the socket function.Next, use sendto and recvfrom, which take the same arguments as send and recv, but add two arguments to designate the partner station. Thus, the sendto function is as follows.
int sendto (
SOCKET s,
LPSTR lpBuffer,
int nBufferLen,
int nFlags,
LPSOCKADDR lpAddr,
int nAddrLen);
lpAddr points to an address structure where you can specify the name of a specific system and port, or you can specify that the datagram is to be broadcast to a specific set of systems.When using recvfrom, you specify which system or systems (perhaps all) from which you are willing to accept datagrams.
Using Datagrams for Remote Procedure Calls
A common use of datagrams is in the implementation of RPCs. Essentially, in the most common situation, a client sends a request to a server using a datagram. Because delivery is not ensured, the client will retransmit the request if a response (also using a datagram) is not received from the server after a wait period. The server must be prepared to receive the same request several times.The important point is that the RPC client and server do not require the overhead of a stream socket connection; instead, they communicate with simple requests and responses. As an option, the RPC implementation ensures reliability through time-outs and retransmissions, simplifying the application program. Alternatively, the client and server are frequently said to be stateless (they do not maintain any state information about current or pending requests). This means that the effect on the server of executing multiple identical client requests is the same as executing a single request. Again, application design and implementation logic are greatly simplified.
