Unreliable Messages with UDP
UDP is a connectionless protocol—meaning that when a client sends a message, it has no way of knowing whether the server ever receives it, much like mail. In fact, in the UDP world, everyone is a client. There aren't any servers—everyone listens, and everyone sends. Application semantics are required to build up dialog behavior, if that is needed.
.NET reflects this by having only a UdpClient class; there is no UdpListener. The UdpClient class is responsible for listening for incoming requests and sending them. To use the UdpClient class for receiving messages, as in the previous chat sample, you need to join a multicast group, as shown in the following code:
IPAddress multicastAddress = IPAddress.Parse("224.0.0.1");
UdpClient client = new UdpClient( 555 );
client.JoinMulticastGroup(multicastAddress, 100);
Now that you have joined this multicast group, you can receive messages to any client on that multicast group by using the following:
while( true )
{
IPEndPoint endpoint = null;
Byte[] buffer = client.Receive(ref endpoint);
String message = Encoding.ASCII.GetString( buffer );
MessageBox.Show( message );
}
Remember to clean up the code by dropping the multicast group:
client.DropMulticastgroup( multicastAddress );
To send a message, you need to join the multicast group, just as you would to receive:
IPAddress multicastAddress = IPAddress.Parse("224.0.0.1");
IPEndPoint m_RemoteEP = new IPEndPoint( multicastAddress, 555 );
UdpClient client = new UdpClient( 555 );
client.JoinMulticastGroup(multicastAddress, 100);
Next, you need to create an array of bytes that you send as a datagram:
Byte[] buffer = new Byte[txtWords.Text.Length + 1];
int length = Encoding.ASCII.GetBytes(
txtWords.Text.ToCharArray(),
0,
txtWords.Text.Length, buffer, 0);
client.Send(buffer, length, m_RemoteEP);
|