1. Program Description
Today, I learned C # UDP and implemented a very simple UDP transceiver.
The function of this tool is to send UDP messages and listen for UDP messages. Enter the text in the text box on the left, and click the Send Data button to send the UDP message. If you click on the "Receive data" button on the right, the text box on the right will display the data sent to the left. Right button, press once to start listening, press the second stop monitoring.
2. Control layout
The control layout of the program, such as
3. Program code
The C # code of the program is as follows:
using system;using system.collections.generic;using system.componentmodel;using system.data;using system.drawing;using system.linq;using system.text;using system.threading.tasks;using system.windows.forms;//new namespaces are required in this section of code using system.net.sockets;using System.Net;using System.Threading;namespace UDPTest{ public partial class formmain : form { public formmain () { initializecomponent (); } /// <summary> /// Network SERVICE class for UDP send /// </ summary> &Nbsp;private udpclient udpcsend; /// <summary > /// Network Service classes for UDP reception /// </summary> private udpclient udpcRecv; /// <summary> /// button: Send data /// </ Summary> /// <param name= "Sender" ></param > /// <param name= "E" ></param> private void btnsend_click (object sender, Eventargs e) { if (String. Isnullorwhitespace (txtsendmssg.text)) { MessageBox.Show ("Please enter what you want to send first"); return; } // Anonymous Send //udpcsend = new udpclient (0); // automatically assign local IPV4 address // real name Send ipendpoint localipep = new ipendpoint ( ipaddress.parse ("127.0.0.1"), 12345); // native IP, specified port number udpcsend = new udpclient ( LOCALIPEP); thread thrsend = new thread (SendMessage); Thrsend.start (Txtsendmssg.text); } /// <summary> /// Send Information /// </summary> /// <param name= "obj" ></param> private void sendmessage (object obj) { string message = (String) obj; byte[] sendbytes = encoding.unicode.getbytes ( message); ipendpoint remoteipep = new ipendpoint ( ipaddress.parse ("127.0.0.1"), 8848); // sent to the IP address and port number udpcsend.send (sendbytes, sendbytes. LENGTH,&NBSP;REMOTEIPEP); Udpcsend.close (); resettextbox ( TXTSENDMSSG); } <summary> /// switch: True when listening for UDP message phase, otherwise false /// </ summary> bool isudpcrecvstart = false; /// <summary> /// Threads: Constantly listening for UDP messages /// </summary> Thread thrRecv; <summary> /// button: Receive data switch /// </summary> /// <param name= "Sender" ></param> /// <param name= "E" ></param> private void btnrecv_click (Object&nbsP;sender, eventargs e) { if (! Isudpcrecvstart) // not listening, start monitoring { Ipendpoint localipep = new ipendpoint ( ipaddress.parse ("127.0.0.1"), 8848); // native IP and listening port number udpcrecv = new udpclient (LOCALIPEP); thrrecv = new thread (ReceiveMessage ); thrrecv.start (); IsUdpcRecvStart = true; showmessage (txtrecvmssg, "UDP listener started successfully"); } else // is listening, stop monitoring { thrrecv.abort (); // must close this thread first, or it will be abnormal udpcrecv.close (); isudpcrecvstart = false; showmessage (txtrecvmssg, "UDP listener successfully closed"); } } /// <summary> /// Receive data /// </summary> /// <param name= "obj" ></param> Private void receivemessage (object obj) { ipendpoint remoteipep = new ipendpoint (ipaddress.any, 0); while (True) { try { byte[] bytrecv = udpcrecv.receive ( REF&NBSP;REMOTEIPEP); string message = encoding.unicode.getstring ( bytrecv, 0, bytrecv.length); showmessage (txtRecvMssg, &nbsP; string . Format ("{0}[{1}]", remoteipep, message)); } catch (Exception ex) { showmessage (Txtrecvmssg, ex. Message); break; } } } // adding text to a textbox Delegate void showmessagedelegate (textbox txtbox, string message); private void showmessage (textbox txtbox, string message ) { if (Txtbox. invokerequired) { ShowMessageDelegate showmessagedelegate = showmessage; txtbox. Invoke (SHOWMESSAGEDELEGATE,&NBSP;NEW&NBSP;OBJECT[]&NBSP;{&NBSP;TXTBOX,&NBSP;MESSAGE&NBSP;}); } else { txtbox. text += message + "\ r \ n"; } } Clears the text in the specified textbox delegate void Resettextboxdelegate (Textbox txtbox); private void resettextbox (Textbox txtbox) { if (Txtbox. invokerequired) { resettextboxdelegate resettextboxdelegate = resettextbox; txtbox. Invoke (RESETTEXTBOXDELEGATE,&NBSP;NEW&NBSP;OBJECT[]&NBSP;{&NBSP;TXTBOX&NBSP;}); } else { txtbox. text = ""; } } /// <summary> /// Close Programs, Force exit /// </summary> ///&nbsP;<param name= "Sender" ></param> /// < Param name= "E" ></param> private void Formmain_formclosing (object sender, formclosingeventargs e) { environment.exit (0); } }}
4. Other
Before you close UdpClient (call its close function), be sure to turn off the thread that listens for UDP, otherwise you will get an error: "A blocking operation is interrupted by a call to WSACancelBlockingCall".
END
C # UDP programming (send and Receive via class UdpClient)