Sunday, December 19, 2010


Creating a simple Chat application


///////Client Application//////// 
A
) Client side: UdpClient udpClient = new UdpClient(); private void Form1_Load(object sender, EventArgs e) { 
udpClient
.Connect("192.168.0.1",15000); // we can use textbox and type other PC IP address 
}
private void button1_Click() { try 
      
{ 
      sendBytes 
= Encoding.ASCII.GetBytes(txtMessage.Text); 
      udpClient
.Send(sendBytes, sendBytes.Length, txtname.Text, 15000);  
      
} 
      
catch (Exception) 
      
{ 
        
throw; 
      
}          } ////////////////Server application////////// 
B
)Server side: delegate void SetTextCallback(string text);
private void Form1_Load(object sender, EventArgs e) 
        
{ 
            
Thread thdUDPServer = new Thread(new ThreadStart(serverThread)); 
            thdUDPServer
.Start(); 
        
}
public void serverThread() { 
            
UdpClient udpClient = new UdpClient(15000); 
            
while (true) 
            
{ 
          
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 15000); 
          
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
          
string returnData = Encoding.ASCII.GetString(receiveBytes); 
    
SetText(RemoteIpEndPoint.Address.ToString() + ":" +                     returnData.ToString()); 
            
} }
private void SetText(string text) {  
    
if (this.lbConnections.InvokeRequired) 
    
{ 
       
SetTextCallback d = new SetTextCallback(SetText); 
       
this.Invoke(d, new object[] { text }); 
    
} 
    
else 
    
{ 
       listBox1
.Items.Add(text); 
    
} }

Creating a simple Chat application: 
It consists of two executables, one a client, the other a server. These two programs 
could be physically separated by thousands of kilometers, but as long as the 
IP addresses of both computers are known, the principle still works.

A) Writing a simple UDP client 
To get started, open Visual Studio .NET, click New Project, then click 
Visual C# projects, and then Windows Application. Set the name to 
�UDP Client� and press OK. You could alternately click Visual Basic .NET 
projects and follow the code labeled VB.NET in the examples. 
Now, design the form and Name the button button1 and the textbox tbHost and 
Second textbox txtMessage.

From the code, we can see that the first task is creating a 
UDP Client object. This is a socket that can send UDP packets. 
A port number is chosen arbitrarily. Here, the port number 15000 is used, 
simply because it is easy to remember and it is not in the first 1024 port numbers, 
which are reserved for special use by IANA. 
The first argument in the Connect method indicates where any data should be sent. 
Here, we can use textbox (i.e., whatever is typed into the textbox). If you have access 
to only one computer, you would type localhost into this window; otherwise, if you are 
using two computers, type the IP address of the server.

Type the message in text box and you can easy to send message 

You also need to include some assemblies by adding these lines to just 
under the lock of the 
using 
statements at the top of the code: 
C# 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
using System.IO;

B) Writing a simple UDP server 
The purpose of the UDP server is to detect incoming data sent from the 
UDP client. Any new data will be displayed in a list box.

As before, create a new C# project, but with a new user interface, as 
shown below. The list box should be named listBox1.

A key feature of servers is multithreading (i.e., they can handle hundreds 
of simultaneous requests). In this case, our server must have at least two 
threads: one handles incoming UDP data, and the main thread of execution 
may continue to maintain the user interface, so that it does not appear hung.

Here, I use delegate to handle the cross thread error.

Again, we use the UdpClient object. Its constructor indicates that it 
should be bound to port 15000, like in the client. The Receive method is
blocking (i.e., the thread does not continue until UDP data is received). In 
a real-world application, suitable timeout mechanisms should be in place 
because UDP does not guarantee packet delivery. Once received, the data is 
in byte array format, which is then converted to a string and displayed onscreen 
in the form source address: data.

There is then the matter of actually invoking the serverThread method 
asynchronously, such that the blocking method, Receive, does not hang 
the application. This is solved using threads as follows:

To finish off, the following assemblies are to be added: 
C# 
using System.Threading; 
using System.Net; 
using System.Net.Sockets; 
using System.Text;

No comments:

Post a Comment