C#UDP programming

Source: Internet
Author: User

one. UDP Protocol

UDP (user Datagram Protocol) protocol is a "Subscriber datagram Protocol", which is a non-connected protocol, and no connection is primarily compared to the TCP protocol. We know that when transmitting data using the TCP protocol, it is first necessary to establish a connection (the so-called handshake) to transmit the data. When the computer uses the UDP protocol for data transmission, the sender only needs to know the IP address and port number of the other party to send the data, and does not need to connect.

because the UDP protocol does not require a deterministic connection, writing a UDP-based application is simpler than writing a TCP-protocol-based application (there is no need to consider connection and some exception capture work in the program). But at the same time, it also brings a fatal disadvantage to the program based on UDP protocol, because UDP does not provide reliable data transmission, when the computer transmits data using UDP protocol, the sender sends the data without confirming whether the data is received by the other party. This causes some UDP protocol packets to be lost during delivery, especially if the network quality is unsatisfactory, and the loss of packets is more serious. This is why transmitting important data over the network does not take the UDP protocol.

visible UDP is a non-connection-oriented network protocol, both its advantages and disadvantages, as follows:

1. UDP protocol-based network applications, the implementation is relatively simple, and UDP protocol-based network applications at run time, due to environmental impact is small, so it is not prone to error.

2.UDP The protocol occupies less network resources, the data processing is faster, so it is obvious that the security requirement is not very high in the network. The so-called security requirements of data, refers to those unimportant data, or even if the loss of some data, it does not affect the overall data, such as audio data. At present, many popular network applications are based on UDP protocol, such as OICQ, ICQ and so on.

3. because it is not a connection-oriented network protocol, its shortcomings are very obvious, sometimes even deadly. Because the UDP protocol is used to transmit data, after the data is sent, the sender does not confirm that the other party is receiving it. This can cause the transmitted data to be lost in the network, especially if the network conditions are not very good, the phenomenon of packet loss is more. So transmitting important data generally does not use the UDP protocol.

Two. C# The main classes used to send and receive UDP packets and their usage

with Visual C# Implementation of the UDP protocol, the most common and most critical class is udpclient,udpclient in the namespace System.Net.Sockets, Visual C # sends, UDP packets are received through the UdpClient class.

table -1 Common methods in UdpClient class and their descriptions

Method

Description

Close

Turn off UDP connections

Connect

Establish a connection to a remote host

Dropmulticastgroup

Exiting a multicast group

Joinmulticastgroup

Add udpclient to a multicast group

Receive

returns a UDP datagram that has been sent by a remote host

Send

Sending a UDP datagram to a remote host

table -2: Common Properties in the UdpClient class and their descriptions

Property

Description

Active

Gets or sets a value that indicates whether a connection to the remote host has been established

Client

Gets or sets the underlying network socket

1. C# send UDP packets using the UdpClient class

In the specific use, generally divided into two kinds of situations:

(1) know the remote computer IP address:

Send the invocation syntax for the method is as follows:

Publicint Send (byte[] dgram, int bytes, ipendpoint endPoint);

parameter description:

Dgram the datagram of the UDP datagram to be sent , expressed in a byte array.

bytes the number of bytes in the datagram.

EndPoint a IPEndPoint type that represents the host IP and port to which the datagram is to be sent.

Returns the number of bytes that the value has been sent.

Here is an example of a specific invocation using UdpClient to send UDP packets:

Ipaddresshostip = new Ipaddress.parse ("192.168.0.188"); ipendpointhost = new IPEndPoint (HostIP, 10002); Udpclient.send ("Bytes Sent", "bytes Sent", host);

(2) know the remote computer name

Send the invocation syntax for the method is as follows:

Publicint Send (byte[] dgram, int bytes, string hostname, int port);

parameter Description:

Dgram the datagram of the UDP datagram to be sent , expressed in a byte array.

bytes the number of bytes in the datagram.

hostname The name of the remote host to connect to.

Port the remote port number to communicate with.

Returns the number of bytes that the value has been sent.

2. C# to receive UDP packets using the UdpClient class:

receiving UDP packets is using the Receive method in UdpClient, which has the following invocation syntax:

Publicbyte [] Receive (ref ipendpoint remoteEP);

Parameters

remoteEP is an instance of the IPEndPoint class that represents the node in the network where this packet is sent.

Here is an example of a specific invocation using UdpClient to receive UDP packets:

Server= new UdpClient (); receivepoint= new IPEndPoint (New IPAddress (127001), 8080); byte[]recdata = Server. Receive (ref receivepoint);


Three. UDP client code,the client program is mainly to send data to the server side

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net;using        System.net.sockets;namespace udpclient{class UdpClient {private UdpClient client;        Private IPEndPoint Receivepoint;            Send data function public void Start_client () {Console.WriteLine ("Client-initiated");            Client = new UdpClient (8080);//clients use 8080 port to send data Receivepoint = new IPEndPoint (new IPAddress (127001), 10002);            IPAddress HostIP;            bool Continueloop = true;                while (Continueloop) {System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding ();                String sendstring = Console.ReadLine (); byte[] SendData = encode.                GetBytes (sendstring);                    try {hostip = Ipaddress.parse ("127.0.0.1"); IPEndPoint host = new IPEndPoint (HostIP, 10002); Server-side sockets, the client sends data to this socket client.        Send (SendData, Senddata.length, host);            byte[] Recdata = client. Receive (ref Receivepoint);//The client uses port 8080, and the receiving server sends data Console.WriteLine (encode) from Port 10002.                    GetString (Recdata));                Continueloop = false; }catch{client.                    Close ();                Return            }}}} class program {static void Main (string[] args) {            UdpClient udpclient = new UdpClient ();        Udpclient.start_client (); }    }}

Four. UDP server-side code,Server-side program is mainly to receive the data sent by the client

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net;using        System.net.sockets;using System.threading;namespace udpserver{class Udpserver {private UdpClient server;               Private IPEndPoint Receivepoint;        Private Thread StartServer; Accept data function Start_server public void Start_server () {Console.WriteLine ("Udpserver start ...            ");                while (true) {asciiencoding encode = new ASCIIEncoding (); byte[] Recdata = server. Receive (ref Receivepoint);//The server receives the packet sent from Port 10002 receivepoint string read_str = encode.                GetString (Recdata);                Console.WriteLine (READ_STR); byte[] SendData = encode.                GetBytes ("OK"); Server. Send (SendData, senddata.length, receivepoint);//server sends data to client's 8080 port}}//Create a thread public VO ID run () {//Use local port number to initialize a UDP network service server = new UdpClient (10002);Local port number, the client sends data to the server's port 10002, the server receives data from port 10002 receivepoint = new IPEndPoint (new IPAddress (127001), 8080);            The client socket startserver = new Thread (new ThreadStart (Start_server));        Start thread Startserver.start (); }} class Program {static void Main (string[] args) {Udpserver udpserver = new            Udpserver ();        Udpserver.run (); }    }}


C#UDP programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.