1. Summary
Summarize synchronous communication based on C# UDP protocol.
2. Experimental platform
Visual Studio 2010
3. Experimental principle
The difference between UDP transmission protocol and TCP transmission protocol can be found in the relevant documents, and will not be described here.
IV. Examples
4.1 Using socket to implement UDP
Because UDP is a connectionless protocol. Therefore, in order for the server application to send and receive UDP packets, two things need to be done:
(1) Create a Socket object;
(2) Bind the created socket object with the local IPEndPoint.
After completing the above steps, the created socket can receive incoming UDP packets on IPEndPoint, or send out outgoing UDP packets to any other device in the network. When using UDP for communication, no connection is required. Because no connection is established between hosts in other places, UDP cannot use the standard Send() and Receive() t socket methods, but uses two other methods: SendTo() and ReceiveFrom().
The SendTo() method specifies the data to be sent and the IPEndPoint of the target machine. This method has many different usage methods, and can be selected according to the specific application, but at least the data packet and the target machine must be specified. as follows:
SendTo(byte[] data,EndPoint Remote)
The ReceiveFrom() method is similar to the SendTo() method, but the method of using the EndPoint object declaration is different. Using ref modification, the passed parameter is not an EndPoint object, but a parameter is passed to an EndPoint object.
UDP applications are not real servers and clients in the strict sense, but equal relationships, that is, no primary and secondary relationships. For simplicity, the following application is still called UDP server.
Server-side code:
using System; using ; using ; using ; using ; namespace UDP { class Program { static void Main(string[] args) { int recv; byte[] data = new byte[1024]; //Get the local IP and set the TCP port number IPEndPoint ip = new IPEndPoint(, 8001); Socket newsock = new Socket(, , ); //Bind network address (ip); ("This is a Server, host name is {0}", ()); //Waiting for the client to connect ("Waiting for a client"); //Get client IP IPEndPoint sender = new IPEndPoint(, 0); EndPoint Remote = (EndPoint)(sender); recv = (data, ref Remote); ("Message received from {0}: ", ()); ((data, 0, recv)); //After the client connection is successful, send the message string welcome = "Hello ! "; //Convert strings and byte arrays to each other data = (welcome); //Send information (data, , , Remote); while (true) { data = new byte[1024]; //Send and receive information recv = (data, ref Remote); ((data, 0, recv)); (data, recv, , Remote); } } } }
For UDP server programs receiving incoming flows, the program must be bound to the UDP port specified in the local system. This allows you to create an IPEndPoint object with the appropriate local IP address, as well as the appropriate UDP port number. The UDP server in the above example program can receive any incoming UDP packets from the network on port 8001.
UDP client programs are very similar to server programs.
Because the client does not need to wait for incoming data on the specified UDP port, the Bind() method is not used, but uses a UDP port randomly specified by the system when the data is sent, and uses the same port to receive the returned message. When developing a product, specify a set of UDP ports for the client so that the server and client programs use the same port number. The UDP client program first defines an IPEndPoint, and the UDP server will send data packets to this IPEndPoint. If you run the UDP server program on a remote device, you must enter the appropriate IP address and UDP port number information in the IPEndPoint definition.
Client code:
using System; using ; using ; using ; using ; using ; namespace UDPClient { class Program { static void Main(string[] args) { byte[] data = new byte[1024]; string input, stringData; //Build TCP server ("This is a Client, host name is {0}", ()); //Set the service IP and set the TCP port number IPEndPoint ip = new IPEndPoint(("127.0.0.1"), 8001); //Define network type, data connection type and network protocol UDP Socket server = new Socket(, , ); string welcome = "Hello! "; data = (welcome); (data, , , ip); IPEndPoint sender = new IPEndPoint(, 0); EndPoint Remote = (EndPoint)sender; data = new byte[1024]; //For non-existent IP addresses, after adding this line of code, the blocking mode limit can be unblocked within a specified time int recv = (data, ref Remote); ("Message received from {0}: ", ()); ((data, 0, recv)); while (true) { input = (); if (input == "exit") break; ((input), Remote); data = new byte[1024]; recv = (data, ref Remote); stringData = (data, 0, recv); (stringData); } ("Stopping Client."); (); } } }
The implementation logic of the above code is: after the relevant settings are completed, the server first sends information to the client, and then the client sends a string through the keyboard, and then sends it to the client after receiving it, which loops in this way.
4.2 Implemented using UDPClient class
Server-side code:
using System; using ; using ; using ; public class Custom { // Set IP, IPV6 private static readonly IPAddress GroupAddress = ("IP address"); // Set the port private const int GroupPort = 11000; private static void StartListener() { bool done = false; UdpClient listener = new UdpClient(); IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort); try { //IPV6, multicast (GroupAddress); (groupEP); while (!done) { ("Waiting for broadcast"); byte[] bytes = (ref groupEP); ("Received broadcast from {0} :\n {1}\n", (), (bytes, 0, )); } (); } catch (Exception e) { (()); } } public static int Main(String[] args) { StartListener(); return 0; } }
Client code:
using System; using ; using ; using ; public class Client { private static IPAddress GroupAddress = ("IP address"); private static int GroupPort = 11000; private static void Send(String message) { UdpClient sender = new UdpClient(); IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort); try { ("Sending datagram : {0}", message); byte[] bytes = (message); (bytes, , groupEP); (); } catch (Exception e) { (()); } } public static int Main(String[] args) { Send(args[0]); return 0; } }
What needs to be explained in the above code is:
(1) The above code is based on the multicast mode of IPV6 address. Broadcast in IPv4 can lead to network performance degradation or even broadcast storm. There is no concept of broadcasting in IPv6, and instead it is multicast and anycast.
(2) IPV6 address representation method:
a) X:X:X:X:X:X:X:X (Each X represents a 16-bit hexadecimal number), case-insensitive;
b) The 0 at the front can be omitted, for example, 09C0 can be written as 9C0, and 0000 can be written as 0;
c) Continuous fields with 0 can be replaced by::, but :: can only appear once in the entire address. For example, FF01:0:0:0:0:0:0:0:0:0:0:0:0:1 can be abbreviated as FF01::1.
(3) If you are using the form, it is recommended to use this format, otherwise you may crash when receiving data.
// Create a child thread Thread thread = new Thread( delegate() { try { //Write your code here } catch (Exception ) { } } ); ();
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.