Implementation of sharing UdpClient online in. NET Applications

Source: Internet
Author: User

Download the original code: MutualUdpClientSample_jb51net.rar

When developing a system that communicates with remote devices, UDP is often used as the medium for data transmission to improve data transmission efficiency. The UdpClient object provided in. NET framework can help developers enable UDP socket points based on system requirements, and quickly establish a UDP online interface to provide communication with remote devices.

In this system architecture, when a different type of remote device is added, a different UDP socket point must be provided for communication with different types of remote devices, when there are more and more remote devices, the UDP socket points required by the system will increase according to the remote device type.

In scenarios with more and more remote devices, the same UDP socket point must be used to communicate with remote devices when the system and remote devices are restricted for network management, then, the packet content or IP address is used to determine the reason for the actually connected remote device.

Copy codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{
// Aggreger
UdpClient udpClientA = new UdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));

UdpClient udpClientB = new UdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));
}
}

According to system requirements, developers may write the program code listed above and directly create two UdpClient objects to enable the same UDP socket point. The content of this program code can be checked by compiling the program, but after you press and execute it, the exception notification of SocketException will be displayed in Visual Studio, it is used to inform developers that the same socket point can only be enabled once. Using two UdpClient to enable the same socket point cannot be executed.

If a developer who has omitted the Design pattern content encounters a resource object that can only have one entity, he or she will think of applying Singleton Pattern to provide the resource object sharing function. In the system, the UDP socket point enabled by the UdpClient object is a resource that can only be enabled by one object. In this scenario, applying Singleton Pattern on the UdpClient object seems to be a good choice.

Copy codeThe Code is as follows: class Program
{
// Singleton
Private static UdpClient _ udpClientInstance = null;

Private static UdpClient UdpClientInstance
{
Get
{
If (_ udpClientInstance = null)
{
_ UdpClientInstance = new UdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));
}
Return _ udpClientInstance;
}
}

// Main
Static void Main (string [] args)
{
// Aggreger
UdpClient udpClientA = Program. UdpClientInstance;

UdpClient udpClientB = Program. UdpClientInstance;

// Transmiter
UdpClient transmiter = new UdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 9999 ));

// Send
Transmiter. Send (new byte [] {55}, 1, new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));

// Receive
Byte [] packet = null;
IPEndPoint remoteEndPoint = new IPEndPoint (IPAddress. Any, IPEndPoint. MinPort );

Packet = udpClientA. Receive (ref remoteEndPoint );
Console. WriteLine (string. Format ("UdpClientA Receive: {0}", packet [0]);

Packet = udpClientB. Receive (ref remoteEndPoint );
Console. WriteLine (string. Format ("UdpClientB Receive: {0}", packet [0]);

// End
Console. ReadLine ();

// Close
Transmiter. Close ();
UdpClientB. Close ();
UdpClientA. Close ();
}
}

Apply Singleton Pattern to the UdpClient object used in the system to write the program code in the upper column, the UdpClient objects used in the system are all shared UdpClient objects statically stored in the system. The content of this program code can be checked by compiling the program, and no exception notification of SocketException will appear during execution, because applying Singleton Pattern allows the system to only enable UDP socket points once.

However, in an advanced step, we will consider the packet receiving function of the UdpClient object. The UdpClient object provides the Receive method to wait for and Receive data packets sent by remote devices, after receiving the data packet, the Receive method will continue to wait and Receive the next data packet. That is to say, a data packet sent by a remote device, UdpClient can only be obtained once through the Receive method, share the same UdpClient object in the system, there is no way to share the data packet obtained by the Receive method.

Observe the execution results of the preceding example and find that the data packets transmitted by transmiter In the example are not received by UdpClientA through the Receive method, in this example, Singleton Pattern is applied to the UdpClient used in the system, and data packets cannot be shared.

To enable the system to use the same UDP socket point to communicate with remote devices, the packet content or IP address is used to determine what the remote devices are actually connected. The author designs a solution named MutualUdpClient, which is used to share data packets transmitted by remote devices through UDP communication.

In the MutualUdpClient solution, use the Singleton Pool Mode published in the previous blog to enable the system to share the UdpClient online, in addition, when a system object uses UdpClient to connect to the Internet, the shared UDP communication is enabled. However, if a system object does not need UdpClient to connect to the Internet, the shared UDP communication is disabled.

.

The Singleton Pool Mode solves the problem of sharing UdpClient online functions. In the MutualUdpClient solution, a RouteUdpClient object is added between UdpClient and MutualUdpClient to share data packets transmitted by remote devices.

The RouteUdpClient object is an active object. After it is established, an independent thread is enabled to continuously receive data packets received by the UdpClient, in addition, each MutualUdpClient is notified of the received data packets by means of events. through such a process, the data packets sent by remote devices can be shared among each MutualUdpClient.

When the MutualUdpClient object receives the data packet provided by RouteUdpClient, it first stores the data packet in a queue, and when the Receive method of the MutualUdpClient object is called, then, the data packets are retrieved from the queue and sent back to the call end to provide the data packets sent by remote devices to the call end for subsequent processing. In this way, the MutualUdpClient object created in each system can be obtained through the Receive method, and the data packets transmitted by each remote device.

* Specifically, the MutualUdpClient object is provided using the Receive method instead of the event method to provide data packets, in order to allow developers who use the MutualUdpClient object, when using objects, you can get the same development experience as using UdpClient to reduce the learning time during development.

After processing data packets sent from shared UdpClient online and remote devices, you must also process the function of transmitting data packets to remote devices. In MutualUdpClient, there is no special requirement for transmitting data packets to remote devices. Therefore, you can directly use the Send function of UdpClient to Send data packets to remote devices.

Copy codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{
// Aggreger
MutualUdpClient udpClientA = new MutualUdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));

MutualUdpClient udpClientB = new MutualUdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));

// Transmiter
UdpClient transmiter = new UdpClient (new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 9999 ));

// Send
Transmiter. Send (new byte [] {55}, 1, new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 1234 ));

// Receive
Byte [] packet = null;
IPEndPoint remoteEndPoint = new IPEndPoint (IPAddress. Any, IPEndPoint. MinPort );

Packet = udpClientA. Receive (ref remoteEndPoint );
Console. WriteLine (string. Format ("UdpClientA Receive: {0}", packet [0]);

Packet = udpClientB. Receive (ref remoteEndPoint );
Console. WriteLine (string. Format ("UdpClientB Receive: {0}", packet [0]);

// End
Console. ReadLine ();

// Close
Transmiter. Close ();
UdpClientB. Close ();
UdpClientA. Close ();
}
}

The program code on the top column demonstrates how to use the MutualUdpClient object in the system. In the example, we can see that the program code directly creates two MutualUdpClient objects with the same UDP endpoint, in addition, exceptions of SocketException are not reported during normal execution. However, after the data packets transmitted by the remote device transmiter are received by UdpClientA through the Receive method, UdpClientB can still Receive the same data through the Receive method, this verifies that the MutualUdpClient object provides the functions of shared communication online and shared data packets.

Download the original code: MutualUdpClientSample_jb51net.rar

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.