The udpclient class provides some simple methods for sending and receiving unconnected UDP datagram packets in the blocking synchronous mode. Because UDP has no connection transmission protocol, you do not need to establish a remote host connection before sending and receiving data. However, you can use either of the following two methods to create a default Remote Host:
You can use any method provided in udpclient to send data to a remote device. The receive method can be used to receive data from a remote host. The udpclient method also allows you to send and receive multicast data packets. You can use the joinmulticastgroup method to reserve a udpclient to a multicast group. You can use the dropmulticastgroup method to cancel a subscription to udpclient from a multicast group. |
/// <Summary> /// client /// </Summary> class udpsender {static void main (string [] ARGs) {// create a udpclient object, 0 indicates that the system automatically assigns the sending port udpclient udpsender = new udpclient (0); // connects to the specified port udpsender on the server. connect ("localhost", 11000); // converts a message into a word and sends it to the server byte [] sendbytes = encoding. ASCII. getbytes ("Is anybody there? "); Udpsender. Send (sendbytes, sendbytes. Length); // close the link udpsender. Close ();}}
/// <Summary> /// server // </Summary> class udpreceive {static void main (string [] ARGs) {// create a udpclient object, 11000 set the receiving port udpclient udpreceive = new udpclient (11000); // set the remote host (IPaddress. any, 0) indicates receiving data sent from all IP Ports ipendpoint remoteipendpoint = new ipendpoint (IPaddress. any, 0); // or ipendpoint remoteipendpoint = NULL; // listen for data. After receiving the data, convert the data into a string and output byte [] receivebytes = udpreceive. receive (ref remoteipendpoint); string returndata = encoding. ASCII. getstring (receivebytes); console. writeline ("this is the message you have Ed" + returndata. tostring (); console. writeline ("this message was sent from" + remoteipendpoint. address. tostring () + "on their port number" + remoteipendpoint. port. tostring (); // close the connection udpreceive. close ();}}
Note: You need to run the server before running the client. Otherwise, the client sends data before the server runs, and the server does not receive the data.