15.6 Creating a Connectionless UDP-Based Client

 <  Day Day Up  >  

You want to create a client application that can communicate with other computers using UDP .


Technique

UDP is merely a protocol that enables the exchange of datagrams between two computers. You can use the UdpClient class in both server and client applications. It means that sending and receiving data for a client application is the same process. All that you need is an IP address and port to send data to and a subsequent call to the Receive method, which fills in the details of the connecting application in the IPHostEntry object when the method returns. In Listing 15.9, you can see the code for a client application designed to work with the server from Listing 15.7. It is a Windows Forms application, which means that any blocking calls on the UdpClient class happen within a thread so that the user interface remains responsive .

When the application initializes, it creates an IPEndPoint object to contain the IP address and port of the server application. Next, it creates a UdpClient object by specifying an IPEndPoint whose IP address and port number are generated automatically to avoid any collisions with clients that might already be running on the same machine. After the UdpClient is created, the application creates the thread that listens for incoming data, whose functionality is contained within the thread procedure ReceiveBroadcast . If you compare this method with the Run method from the server, you'll see that the actual process of receiving data using a UdpClient is the same, regardless of whether the application is a server or a client. Likewise, sending data is also the same. The client application only has to deal with sending and receiving data with a single IP address, the server.

Listing 15.9 The UDP Chat Client Application
 using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; namespace _5_UDPFormClient {     public class Form1 : System.Windows.Forms.Form     {         private System.Windows.Forms.TextBox tbTranscript;         private System.Windows.Forms.TextBox tbMessage;         private System.Windows.Forms.Button btnSend;         private Thread chatThread;         private System.ComponentModel.Container components = null;         private string name;         UdpClient client;         private System.Windows.Forms.TextBox tbName;         private System.Windows.Forms.Label label1;         private System.Windows.Forms.Button btnSetName;         IPEndPoint serverIP;         public Form1()         {             InitializeComponent();             serverIP = new IPEndPoint( IPAddress.Parse( "127.0.0.1" ), 2003 );             client = new UdpClient( new IPEndPoint( IPAddress.Any, 0 ));             name = tbName.Text;             // create a thread to start receiving broadcast messages             chatThread = new Thread( new ThreadStart( ReceiveBroadcast ));             chatThread.Start();             SendCommand( "300 " + name );         }         public void ReceiveBroadcast()         {             IPEndPoint receiveIP = new IPEndPoint(IPAddress.Any, 0);             while( true )             {                 byte[] data = client.Receive( ref receiveIP );                 tbTranscript.Text += Encoding.ASCII.GetString( data,                     0, data.Length ) + "\r\n";             }         }         protected override void Dispose( bool disposing )         {             if( disposing )             {                 if (components != null)                 {                     components.Dispose();                 }             }             base.Dispose( disposing );         }         private void InitializeComponent()         {             this.tbTranscript = new System.Windows.Forms.TextBox();             this.tbMessage = new System.Windows.Forms.TextBox();             this.btnSend = new System.Windows.Forms.Button();             this.tbName = new System.Windows.Forms.TextBox();             this.label1 = new System.Windows.Forms.Label();             this.btnSetName = new System.Windows.Forms.Button();             this.SuspendLayout();             // Windows Form initialization code removed             this.ResumeLayout(false);         }         [STAThread]         static void Main()         {             Application.Run(new Form1());         }         private void SendCommand( string command )         {             byte[] bytes = Encoding.ASCII.GetBytes(command);             int ret = client.Send(bytes, bytes.Length, serverIP );         }         private void btnSend_Click(object sender, System.EventArgs e)         {             SendCommand( "400 " + tbMessage.Text );         }         private void btnSetName_Click(object sender, System.EventArgs e)         {             SendCommand( "301 " + name );             SendCommand( "300 " + tbName.Text );             name = tbName.Text;         }         private void Form1_Closed(object sender, System.EventArgs e)         {             SendCommand( "301 " + name );         }     } } 

Comments

The previous section used the UdpClient class to perform the functions of a server. Because UDP is a connectionless protocol, the line between server and client becomes a little fuzzy. Because the whole purpose of UDP is to send a message from one computer to the other, a client/server architecture doesn't necessarily have to be your design. Some applications might only use a server as an intermediary to introduce two clients to each other. Once it makes this connection, the two clients can simply send and receive datagram messages back and forth with each other.

The client application in Listing 15.9 performs its interaction with the server from Listing 15.7. The only messages the client sends and receives are from the server itself. It is up to the server to properly broadcast messages from a client to all the other clients. Again, this arrangement is purely a design decision based on the fact that the chat application should act more like a chat room rather than an instant messenger, which performs one-on-one communication between two clients.

 <  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