C # Network Programming series (eight) UdpClient implementation of synchronous UDP server

Source: Internet
Author: User

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 a synchronous UDP server

UdpClient Synchronous UDP Server


Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets;using  System.net;using system.threading;namespace netframe.net.udp.listener.synchronous{//<summary>//UdpClient        Implementing a synchronous UDP server///</summary> public class Udpserver {#region fields//<summary>        Maximum number of client connections allowed by the server program//</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<udpstate> _clients;        private bool disposed = false;        <summary>///Data reception buffer///</summary> private byte[] _recvbuffer; #endregion #region Properties//<summary>///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>///Synchronous UdpClient UDP Server///</summary> <param name= "listenport" > Monitored ports </param> public udpserver (int listenport): This (ipaddre Ss. Any, listenport,1024) {}//<summary>//Sync udpclient UDP server///&LT;/SUMMARY&G        T <param name= "localEP" > Monitoring endpoint </param> public udpserver (IPEndPoint localEP): This (localep . Address, Localep.port,1024) {}///<summary>///sync udpclient UDP server///</summary>//        <param name= "localipaddress" > IP address of the listener </param>//<param name= "Listenport" > Listening ports </param> <param name= "maxclient" > Maximum number of clients </param> public udpserver (IPAddress localipaddress, int listenp ORT, 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; New Thread (Receivedata).            Start ();            }}///<summary>//Stop server///</summary> public void Stop () {                if (isrunning) {isrunning = false; _server.                Close ();        TODO closes the connection to all clients}}///<summary>//////</summary> <param name= "ar" ></param> private void Receivedata () {IPEndPoint remote = null            ;                while (true) {byte[] buffer = NULL; try {buffer = _server.                Receive (ref remote);                } catch (Exception) {//exception handling operation return; } if (buffer = = NULL | | buffer. Length = = 0) return;                TODO Packet received trigger event raisedatareceived (NULL); }}////<summary>////<param name= "MSG" >&lt        ;/param>//<param name= "remote" ></param> public void Send (String msg, IPEndPoint remote)            {byte[] data = Encoding.Default.GetBytes (msg); try {_server. Send (data, data.            Length, remote);            } catch (Exception) {//todo exception handling raiseotherexception (NULL); }} #endregion Events #region///<summary>///</summary&gt        ;        public event eventhandler<udpeventargs> DataReceived; private void raisedatareceived (Udpstate state) {if (datareceived! = null) {D            Atareceived (This, new Udpeventargs (state));       }        } <summary>///Data Send complete Event///</summary> public event eventhandler<udpeventargs>        Completedsend;         <summary>///Trigger data sent events///</summary>//<param name= "state" ></param>                private void Raisecompletedsend (Udpstate state) {if (completedsend! = null) {            Completedsend (This, new Udpeventargs (state)); }}///<summary>//Network error events///</summary> public event Eventhandler<ud        Peventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param> private void Raiseneterror (Udpstate state) {if (neterror! = null) {Nete            Rror (This, new Udpeventargs (state)); }}///<summary>///exception events///</summary> public evenT eventhandler<udpeventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param>            private void Raiseotherexception (udpstate state, String descrip) {if (otherexception! = null)            {Otherexception (this, new Udpeventargs (Descrip, state));        }} private void Raiseotherexception (Udpstate state) {raiseotherexception (State, ""); #endregion #region Close//<summary>//Close a session with the client///</summary&        Gt <param name= "State" > Client Session object that needs to be closed </param> public void close (udpstate 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 Disp OSE (bool disposing) {if (!this.disposed) {if (disposing) {try {                        Stop ();                        if (_server! = null) {_server = null;                        }} catch (SocketException) {//todo                    Raiseotherexception (NULL);            }} disposed = true; }} #endregion}}


User state Encapsulation 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.synchronous{public    class Udpstate    {        //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.synchronous{//<summary>//udpclient Synchronous UDP Server event class///</summary> Publ IC class Udpeventargs:eventargs {///<summary>////</summary> Publi        C string _msg;        <summary>///Client Status Package class////</summary> public udpstate _state;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Udpeventargs (String msg) {this._msg = msg;        ishandled = false;            Public Udpeventargs (udpstate state) {this._state = state;        ishandled = false;            } public Udpeventargs (String msg, udpstate state) {this._msg = msg;            This._state = State;        ishandled = false; }    }}

The above is the C # network programming series (eight) UdpClient implementation of the content of the synchronization UDP server, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.