This article mainly introduces the C #-based UDP protocol synchronous implementation code, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.
I. Summary
Summarizes the synchronous communication of the UDP protocol based on C #.
Second, the experimental platform
Visual Studio 2010
Three, the principle of experiment
The difference between the UDP transport protocol and the TCP transport protocol can be found in the relevant documentation, which is not mentioned here.
Iv. examples
4.1 Using sockets for UDP
Because UDP is a non-connected protocol. Therefore, in order for the server application to be able to send and receive UDP packets, there are two things to do:
(1) Create a socket object;
(2) binds the created socket object to the local ipendpoint.
After completing the above steps, the created socket can either receive incoming UDP packets on IPEndPoint or send outgoing UDP packets to any other device on the network. When using UDP for communication, no connection is required. Because there is no connection between hosts in the offsite, UDP cannot use the standard send () and receive () t socket methods, but instead uses two other methods: SendTo () and ReceiveFrom ().
The SendTo () method specifies the data to be sent, and the ipendpoint of the target machine. There are several different ways to use this method, which can be selected according to the specific application, but at least the data packet and target machine must be specified. As follows:
SendTo (byte[] data,endpoint Remote)
The ReceiveFrom () method is similar to the SendTo () method, but uses endpoint object declarations differently. Instead of a endpoint object, the ref modifier passes a parameter to a endpoint object.
UDP applications are not strictly real servers and clients, but equal relationships, that is, no primary and secondary relationships. For simplicity, the following application is still referred to as a UDP server.
Server-side code:
Using system;using system.collections.generic;using system.text;using system.net;using System.Net.Sockets;namespace Udp{class Program {static void Main (string[] args) {int recv; byte[] data = new byte[1024]; Get the native IP, set the TCP port number ipendpoint IP = new IPEndPoint (Ipaddress.any, 8001); Socket Newsock = new socket (addressfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP); Bind network Address Newsock. Bind (IP); Console.WriteLine ("This was a Server, host name is {0}", Dns.gethostname ()); Wait for the client to connect Console.WriteLine ("Waiting for a Client"); Get the client IP ipendpoint sender = new IPEndPoint (ipaddress.any, 0); EndPoint Remote = (EndPoint) (sender); recv = Newsock. ReceiveFrom (data, ref Remote); Console.WriteLine ("Message received from {0}:", remote.tostring ()); Console.WriteLine (Encoding.ASCII.GetString (data, 0, recv)); After the client connection succeeds, send the message string welcome = "Hello!"; Strings and byte arrays convert data = Encoding.ASCII.GetBytes (welcome); Send Message Newsock. SendTo (data, data. Length, SockEtflags.none, Remote); while (true) {data = new byte[1024]; Send Receive Message recv = Newsock. ReceiveFrom (data, ref Remote); Console.WriteLine (Encoding.ASCII.GetString (data, 0, recv)); Newsock. SendTo (data, recv, Socketflags.none, Remote); } } }}
For incoming UDP server programs, the program must be bound to the UDP port specified on the local system. This can be done by creating a IPEndPoint object with the appropriate local IP address and the appropriate UDP port number. The UDP server in the example program above can receive any incoming UDP packets from the network on port 8001.
A UDP client program is very similar to a server program.
Because the client does not need to wait for incoming data on the specified UDP port, instead of using the bind () method, it uses a UDP port that is randomly specified at the time the data is sent, and receives the returned message using the same port. When you develop a product, you 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 a IPENDPOINT,UDP server that will send packets to this ipendpoint. If you are running a 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 system.collections.generic;using system.linq;using system.text;using System.Net;using System.net.sockets;namespace udpclient{class Program {static void Main (string[] args) {byte[] data = new byte[1024] ; string input, StringData; Build the TCP Server Console.WriteLine ("This was a Client, host name is {0}", Dns.gethostname ()); Set the service IP, set the TCP port number ipendpoint IP = new IPEndPoint (Ipaddress.parse ("127.0.0.1"), 8001); Define the network type, data connection type, and network protocol UDP socket SERVER = new socket (addressfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP); string welcome = "Hello!"; data = Encoding.ASCII.GetBytes (welcome); Server. SendTo (data, data. Length, Socketflags.none, IP); IPEndPoint sender = new IPEndPoint (ipaddress.any, 0); EndPoint Remote = (EndPoint) sender; data = new byte[1024]; For non-existent IP addresses, after joining this line of code, the blocking mode limit of int recv = Server can be unblocked within a specified time. ReceiveFrom (data, ref Remote); Console.WriteLine ("Message received from {0}:", remote.tostring ()); Console.WriteLine (ENCODING.ASCIi. GetString (data, 0, recv)); while (true) {input = Console.ReadLine (); if (input = = "Exit") break; Server. SendTo (Encoding.ASCII.GetBytes (input), Remote); data = new byte[1024]; recv = Server. ReceiveFrom (data, ref Remote); StringData = Encoding.ASCII.GetString (data, 0, recv); Console.WriteLine (StringData); } Console.WriteLine ("Stopping Client."); Server. Close (); } }}
The implementation logic of the above code is: After the relevant settings, the server sends the message to the client, then the client sends a string through the keyboard, the server receives and then sends to the client, so loop.
4.2 Implemented with the UdpClient class
Server-side code:
Using system;using system.net;using system.net.sockets;using system.text;public class custom{//Set Ip,ipv6 private static readonly IPAddress groupaddress = ipaddress.parse ("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 listener. Joinmulticastgroup (groupaddress); Listener. Connect (GROUPEP); while (!done) { Console.WriteLine ("Waiting for Broadcast"); byte[] bytes = listener. Receive (ref GROUPEP); Console.WriteLine ("Received broadcast from {0}: \ n {1}\n", groupep.tostring (), Encoding.ASCII.GetString (bytes, 0, bytes . Length)); } Listener. Close (); } catch (Exception e) { Console.WriteLine (e.tostring ())} } public static int Main (string[] args) { Startlistener (); return 0; }}
Client code:
Using system;using system.net;using system.net.sockets;using system.text;public class client{private static IPAddress Groupaddress = ipaddress.parse ("IP Address"); private static int groupport = 11000; private static void Send (String message) { UdpClient sender = new UdpClient (); IPEndPoint Groupep = new IPEndPoint (groupaddress, groupport); Try { Console.WriteLine ("Sending datagram: {0}", message); byte[] bytes = Encoding.ASCII.GetBytes (message); Sender. Send (bytes, bytes. Length, GROUPEP); Sender. Close (); } catch (Exception e) { Console.WriteLine (e.tostring ())} } public static int Main (string[] args) { Send (Args[0]); return 0; }}
The above code should explain:
(1) The above code is a multicast mode based on IPV6 address. IPV4 Broadcast (broadcast) can cause network performance degradation or even broadcast storms (broadcast storm). There is no concept of broadcasting in IPV6, instead of multicast (multicast) and anycast (anycast).
(2) IPV6 Address representation method:
A) x:x:x:x:x:x:x:x (each X represents 16 bits of 16 decimal digits), not case sensitive;
b) 0 of the Pai Tau can be omitted, such as 09C0 can be written 9c0,0000 can be written 0;
c) a continuous field of 0 can be replaced by::, but the entire address:: Can only appear once, such as ff01:0:0:0:0:0:0:1 can be abbreviated to FF01::1.
(3) If this format is suggested as a form, the freezing behavior may occur when the data is received.
Create a child thread the thread thread = new Thread ( delegate () { try { //write your code here } catch ( Exception) { } } ); Thread. Start ();