I won't talk much about the UDP principle. I can find a lot on the Internet. Programs are divided into clients and servers. Function: the server receives and displays data from the client.
1. Client
The interface is as follows:
Control names: textboxip, textboxport, textboxtxt, and buttonsend.
The client sends data to the server through the Server IP address and port number. The default IP address is localhost or 127.0.0.1.
Client program code:
Using system;
Using system. text;
Using system. Windows. forms;
Using system. net. Sockets;
Using system. net;
Namespace udpclient
{
Public partial class form1: Form
{
Udpclient UC;
Public form1 ()
{
Initializecomponent ();
UC = new udpclient ();
This. textboxip. Text = "localhost ";
}
Private void buttonsend_click (Object sender, eventargs E)
{
String host = This. textboxip. text;
Int Port = convert. toint32 (this. textboxport. Text );
String TXT = This. textboxtxt. text;
Byte [] B = system. Text. encoding. utf8.getbytes (txt );
If (host = "localhost ")
{
Host = DNS. gethostname ();
}
If (UC! = NULL)
{
UC. Send (B, B. length, host, Port );
}
}
}
}
2. Server Interface
Controls: textboxport, listbox1, and buttonstart
Set the port for receiving data on the server side and click Start. To change the port, start again.
The Code is as follows:
Using system;
Using system. text;
Using system. Windows. forms;
Using system. net. Sockets;
Using system. net;
Using system. Threading;
Namespace udpserver
{
Public partial class form1: Form
{
Udpclient UC = NULL;
Thread th = NULL;
Public form1 ()
{
Initializecomponent ();
// Shield the exception of modifying control attributes across threads
Checkforillegalcrossthreadcils = false;
}
Private void listen ()
{
// Specify the end point, IP address, and port number.
Ipendpoint IEP = new ipendpoint (IPaddress. parse ("192.168.0.147"), 8888 );
While (true)
{
// Obtain the data packet sent by form1
String text = system. Text. encoding. utf8.getstring (UC. Receive (ref IEP ));
// Add to ListBox
This. listbox1.items. Add (text );
}
}
Private void button#click (Object sender, eventargs E)
{
// Note that the port number must be the same as that of the sender.
Int Port = convert. toint32 (this. textboxport. Text );
UC = new udpclient (port );
// Instantiate the thread
Th = new thread (New threadstart (Listen ));
// Set it to the background
Th. isbackground = true;
Th. Start ();
}
Private void textboxport_textchanged (Object sender, eventargs E)
{
// The thread needs to be restarted if the port is changed.
If (Th! = NULL)
{
Th. Abort ();
}
}
}
}