15.5 Creating a Connectionless UDP-Based Server

 <  Day Day Up  >  

You want to create a server that uses the User Datagram Protocol ( UDP ) for connectionless communication to client systems.


Technique

UDP is a connectionless protocol because communication between a server and a client happens using packets of information called datagrams rather than a continuous stream of data. In other words, a stream-based protocol creates a connection and streams data until the session ends. UDP, however, sends packets of information to a specified IP address and port without keeping a continuous connection open .

You use the UdpClient class to facilitate UDP-based communication. This section looks at creating a centralized server to broadcast information to a known group of IP addresses on specific ports. The first step to create the server is to instantiate a UdpClient object on a known port. You can use a default port by not specifying port information within the constructor, but server applications are generally designed to work on a specific port. Therefore, create a new UdpClient and specify the port you want to use, as shown in the constructor of the UDPServer class in Listing 15.7.

Listing 15.7 Creating a UDP Server
 using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections; namespace _5_UDPServer {     class Class1     {         [STAThread]         static void Main(string[] args)         {             UDPServer server = new UDPServer();             server.Run();         }     }     struct ConnectedClient     {         public IPEndPoint ip;         public string name;     }     class UDPServer     {         private UdpClient udp;         private IPEndPoint remoteEndPoint;         private ArrayList clients;         public UDPServer()         {             clients = new ArrayList();             udp = new UdpClient( 2003 );         }     } } 

Once you create the UdpClient , you are ready to begin receiving data. The UdpClient class contains a method named Receive , which accepts a reference to an IPEndPoint object. When the method returns, the IPEndPoint object contains the relevant data concerning the client that sent the data:

 
 public void Run() {     while( true )     {         remoteEndPoint = new IPEndPoint( new IPAddress(0), 0 );         byte[] data = udp.Receive( ref remoteEndPoint );         Console.WriteLine( "Received data: {0}", Encoding.ASCII.GetString( data ));         ProcessMessage( Encoding.ASCII.GetString( data ));     } } 

You can then use this IPEndPoint object as a parameter to the Send method defined in the UdpClient class to reply to the client. This back and forth communication utilizes byte arrays whose data depends on the communication protocol used by the server and client. Listing 15.8 contains the remaining significant methods of the UDPServer class started earlier. The protocol is similar to the TCP server created in Recipe 15.1 in that numeric commands followed by relevant data constitute a command to the server. The server itself implements a chat server that broadcasts chat messages to each client that requests to be added. Each client's information is contained within the private ArrayList collection contained within the server.

Listing 15.8 UDP Chat Server
 private void ProcessMessage( string message )         {             switch( GetResponseCode( message ) )             {                 case (300): // add new user                 {                     ConnectedClient newClient;                     newClient.ip = remoteEndPoint;                     newClient.name = GetResponseData( message );                     clients.Add( newClient );                     BroadcastMessage( newClient.name +                         " has entered the conversation." );                     break;                 }                 case (301): // remove user                 {                     BroadcastMessage( FindName( remoteEndPoint) +                         " has left the conversation." );                     RemoveClient( remoteEndPoint );                     break;                 }                 case( 400 ): // chat message                 {                     BroadcastMessage( FindName( remoteEndPoint ) + ": " +                         GetResponseData( message ) );                     break;                 }             }         }         private void BroadcastMessage( string message )         {             foreach( object obj in clients )             {                 try                 {                     ConnectedClient client = (ConnectedClient) obj;                     udp.Send( Encoding.ASCII.GetBytes( message.ToCharArray ()),                         message.Length, client.ip );                 }                 catch( Exception e)                 {                     Console.WriteLine( e.Message );                 }             }         }     } } 

Comments

Now that you've seen two different technologies, TCP and UDP, that essentially perform the same function, you'll have to determine which one to use in certain instances. The deciding factor is the communication protocol you use. A stream-based server maintains a connection with each client it is servicing , which therefore allows it to maintain some sort of state information for each client. To put it into a physical metaphor, a stream-based server is a lot like a conversation that you are holding with someone. You make the initial connection, begin communicating, and build up a session history until the conversation is over. A UDP-based server, on the other hand, does not follow this convention. You are never guaranteed that a client will keep communicating with you after an initial connection because that connection is immediately dropped after the datagram arrives, thereby making it difficult to maintain state information for each client connecting to the server.

The UdpClient itself uses the methods of the Socket class for communication. As mentioned earlier, UDP uses packets of information known as datagrams to transfer data. However, unlike a stream-based connection where data arrives in sequential order, datagrams not only can arrive out of order but can also be duplicated . It is up to the receiver to place the datagrams back in order. Fortunately, this task is already done for you within the UdpClient class. All that your application has to deal with is the final transferred data.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net