C # Network Programming series article (vii) UdpClient implementing asynchronous UDP servers

Source: Internet
Author: User

Declaration of originality

This article small bamboo zz This address http://blog.csdn.net/zhujunxxxxx/article/details/44258719 reprint please indicate the source

This article describes

The UdpClient class provides an easy way to send and receive non-connected UDP packets in synchronous blocking mode. Because UDP is a non-connected transport protocol, you do not need to establish any remote host connections before sending and receiving data. You only need to set the default remote host options in the following ways:
Use the remote host name and port number as parameters to create an instance of the UdpClient class.
Create an instance of the UdpClient class and call the Connect method.
You can use any of the sending methods provided by UdpClient to send the data to the remote device. Then use the Receive method to receive data from the remote host.
Tip: If you have specified a default remote host, do not use the host name or IPEndPoint to invoke the Send method. If you do this, then UdpClient will throw an exception.
The UdpClient method also allows you to send and receive multicast packets. Using the Joinmulticastgroup method, you can subscribe udpclient to multicast packets. You can also use the Dropmulticastgroup method to cancel a udpclient from a multicast-grouped subscription.

This section describes using UdpClient to implement an asynchronous high-performance UDP server

UdpClient Asynchronous UDP Server

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets;using System.net;namespace netframe.net.udp.listener.asynchronous{//<summary>//UdpClient Implementing an Asynchronous UDP Server///&LT ;/summary> public class Asyncudpserver {#region fields//<summary>//server program maximum allowable customers        Number of end connections//</summary> private int _maxclient;        <summary>///Current number of connected clients///</summary>//private int _clientcount;        <summary>///server uses asynchronous UdpClient///</summary> private udpclient _server;        <summary>///client Session list///</summary>//private list<asyncudpstate> _clients;        private bool disposed = false;        <summary>///Data reception buffer///</summary> private byte[] _recvbuffer;     #endregion #region Properties//<summary>   Whether the server is running///</summary> public bool IsRunning {get; private set;}        <summary>////Listening IP address///</summary> public IPAddress address {get; private set;}        <summary>/////</summary> public int port {get; private set;}        <summary>////</summary> public Encoding Encoding {get; set;}        #endregion #region Constructors//<summary>///asynchronous UdpClient UDP Server///</summary> <param name= "listenport" > Monitored ports </param> public asyncudpserver (int listenport): This (IP Address.any, listenport,1024) {}//<summary>//Asynchronous UdpClient UDP Server///&LT;/S            ummary>//<param name= "localep" > Monitored endpoints </param> public asyncudpserver (IPEndPoint localEP) : This (localep.address, Localep.port, 1024x768) {}//<summary>///asynchronous UdpClient UDP Server///</summary>///        Lt;param name= "localipaddress" > IP address of the listener </param>//<param name= "Listenport" > Listening ports </param> <param name= "maxclient" > Maximum number of clients </param> public asyncudpserver (IPAddress localipaddress, int list Enport, int maxclient) {this.            Address = localipaddress; This.            Port = Listenport; This.            Encoding = Encoding.default;            _maxclient = maxclient;            _clients = new list<asyncudpsocketstate> (); _server = new UdpClient (new IPEndPoint (this. Address, this.            Port)); _recvbuffer=new Byte[_server.        Client.receivebuffersize]; } #endregion #region Method///<summary>///Start server//</summary>/ <returns> Asynchronous TCP Server </returns> public void Start () {if (!    isrunning)        {isrunning = true; _server.                EnableBroadcast = true; _server.            BeginReceive (Receivedataasync, NULL);            }}///<summary>//Stop server///</summary> public void Stop () {                if (isrunning) {isrunning = false; _server.                Close ();        TODO closes the connection to all clients}}///<summary>//////For receiving data//</summary> <param name= "ar" ></param> private void Receivedataasync (IAsyncResult ar) {IPENDP            Oint remote=null;            byte[] buffer = NULL; try {buffer = _server.                EndReceive (AR, ref remote);            Trigger data receive event raisedatareceived (NULL);            } catch (Exception) {//todo handles exception raiseotherexception (NULL); } finAlly {if (isrunning && _server! = null) _server.            BeginReceive (Receivedataasync, NULL); }}///<summary>/////</summary>//<param name= "MSG" ></        param>//<param name= "remote" ></param> public void Send (String msg, IPEndPoint remote)            {byte[] data = Encoding.Default.GetBytes (msg);                try {raisepreparesend (null); _server. BeginSend (data, data.            Length, New AsyncCallback (Sendcallback), null);            } catch (Exception) {//todo exception handling raiseotherexception (NULL); }} private void Sendcallback (IAsyncResult ar) {if (AR. iscompleted) {try {_server.                    EndSend (AR); Message Send Complete Event RaisecomplEtedsend (NULL); } catch (Exception) {//todo data send failed event raiseotherexcept                Ion (NULL); }}} #endregion event #region events///<summary>///</        Summary> public event eventhandler<asyncudpeventargs> datareceived;                private void raisedatareceived (Asyncudpstate state) {if (datareceived! = null) {            DataReceived (This, new Asyncudpeventargs (state)); }}///<summary>///events before sending data///</summary> public event eventhandler<        Asyncudpeventargs> Preparesend;        <summary>///trigger event before data is sent///</summary>//<param name= "state" ></param>                private void Raisepreparesend (Asyncudpstate state) {if (preparesend! = null) { PrepAresend (This, new Asyncudpeventargs (state)); }}///<summary>///Data Send complete Event///</summary> public event eventhandler<        Asyncudpeventargs> Completedsend;         <summary>///Trigger data sent events///</summary>//<param name= "state" ></param>                private void Raisecompletedsend (Asyncudpstate state) {if (completedsend! = null) {            Completedsend (This, new Asyncudpeventargs (state)); }}///<summary>//Network error events///</summary> public event Eventhandler<as        Yncudpeventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param>                private void Raiseneterror (Asyncudpstate state) {if (neterror! = null) {         Neterror (This, new Asyncudpeventargs (state));   }}///<summary>///exception Event///</summary> public event Eventhandler<a        Syncudpeventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param>            private void Raiseotherexception (asyncudpstate state, String descrip) {if (otherexception! = null)            {Otherexception (this, new Asyncudpeventargs (Descrip, state)); }} private void Raiseotherexception (Asyncudpstate state) {raiseotherexception (State, "")        ;        #endregion #region Close//<summary>//Close a session with the client///</summary>            <param name= "State" > Client Session object that needs to be closed </param> public void close (Asyncudpstate state) { if (state = null) {//_clients.                Remove (state);    _clientcount--;            TODO triggers Shutdown Event}}///<summary>///Close all client sessions, and all client connections will be disconnected///             lt;/summary> public void Closeallclient () {//foreach (asyncudpsocketstate client in _clients)            {//Close (client);            }//_clientcount = 0; _clients.        Clear (); } #endregion #region Release//<summary>//performs application-defined tasks associated        With freeing,///releasing, or resetting unmanaged resources.            </summary> public void Dispose () {Dispose (true); Gc.        SuppressFinalize (this); }//<summary>//Releases unmanaged and-optionally-managed resources///&LT;/SUMMARY&GT        ; <param name= "disposing" ><c>true</c> to release//both managed and unmanaged resources; <c>false</c>//To ReleASE only unmanaged resources.</param> protected virtual void Dispose (bool disposing) {if (                        !this.disposed) {if (disposing) {try {                        Stop ();                        if (_server! = null) {_server = null;                        }} catch (SocketException) {//todo                    Raiseotherexception (NULL);            }} disposed = true; }} #endregion}}

The client information encapsulates the class

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets;using System.net;namespace netframe.net.udp.listener.asynchronous{public    class Asyncudpstate    {        //Client   socket.        Public UdpClient udpclient = null;        Size of receive buffer.        public const int buffersize = 1024x768;        Receive buffer.        Public byte[] buffer = new Byte[buffersize];        Received data string.        Public StringBuilder sb = new StringBuilder ();        Public IPEndPoint remote = new IPEndPoint (ipaddress.any, 0);}    }
Server Event Parameter class

Using system;using system.collections.generic;using system.linq;using system.text;namespace netframe.net.udp.listener.asynchronous{//<summary>//UdpClient Asynchronous UDP Server Event parameter class///</summary> P        Ublic class Asyncudpeventargs:eventargs {//<summary>/////</summary>        public string _msg;        <summary>///Client Status Package class////</summary> public asyncudpstate _state;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Asyncudpeventargs (String msg) {this._msg = msg;        ishandled = false;            Public Asyncudpeventargs (asyncudpstate state) {this._state = state;        ishandled = false;            } public Asyncudpeventargs (String msg, asyncudpstate state) {this._msg = msg;            This._state = State; ishandled = FALse }    }}



C # Network Programming series article (vii) UdpClient implementing asynchronous UDP servers

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.