UDP chat code listening server code
Add reference
Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. net;
Using system. net. Sockets;
Using system. text;
Using system. Threading;
/// <Summary>
/// Required designer variables defined by the UDP Connection System
/// </Summary>
Public udpclient;
Private system. Windows. Forms. textbox textbox4;
Private system. Windows. Forms. Label label4;
Private system. Windows. Forms. textbox textbox3;
Private system. Windows. Forms. Label label3;
Public thread udpthread;
Public const int listenport = 12000;
Button event (Listening to messages)
Private void button2_click (Object sender, system. eventargs E)
{
If (udpclient! = NULL)
{
Udpthread. Abort ();
Thread. Sleep (timespan. frommilliseconds (500 ));
Udpclient. Close ();
}
Try
{
Udpclient = new udpclient (Int. parse (textbox2.text ));
Udpthread = new thread (New threadstart (udprecivethread ));
Udpthread. Start ();
}
Catch (exception y)
{
MessageBox. Show (this, Y. message, "error", messageboxbuttons. OK, messageboxicon. Error );
}
}
// Receiving data thread
Public void udprecivethread ()
{
Bool done = false;
Ipendpoint remotehost = new ipendpoint (IPaddress. Any, listenport );
This. statusbar1.text = "Starting listening ...";
While (udpclient! = NULL & thread. currentthread. threadstate. Equals (threadstate. Running ))
{
Try
{
This. statusbar1.text = "waiting for connection ...";
Byte [] Buf = udpclient. Receive (ref remotehost );
String bufs = encoding. utf8.getstring (BUF );
Int listcount = 0;
If (listview1.items. Count = 0)
{
Listview1.items. Add (datetime. Now. tostring ());
Listview1.items [0]. subitems. Add (remotehost. Address. tostring ());
Listview1.items [0]. subitems. Add (bufs );
}
Else
{
Listcount = listview1.items. count;
Listview1.items. Add (datetime. Now. tostring ());
Listview1.items [listcount]. subitems. Add (remotehost. Address. tostring ());
Listview1.items [listcount]. subitems. Add (bufs );
}
This. statusbar1.text = "datagram length:" + bufs. length;
}
Catch (exception y)
{
This. statusbar1.text = "error:" + Y. Message + "" + Y. source;
}
}
This. statusbar1.text = "listening ends ...";
}