C # Network Programming series article (v) Socket implementation asynchronous UDP server

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. Net, the System.Net.Sockets namespace provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need tight control over network access. All other network access classes in the System.Net namespace are built on the socket socket implementation, such as the TcpClient, TcpListener, and UdpClient classes encapsulate details about creating TCP and UDP connections to the Internet The NetworkStream class provides the underlying data flow for network access, and many common Internet services can see the sockets, such as Telnet, Http, Email, Echo, and so on, although the definition of the Communication protocol protocol is different , but the base of the transmission is the socket used. In fact, a socket can be treated like a stream stream as a data channel, which is placed between the application side (client) and the remote server, and then the read (receive) and write (send) of the data are directed at this channel.
It can be seen that after the application side or the server side created the socket object, it is possible to use the Send/sentto method to send data to the connected socket, or use the Receive/receivefrom method to receive data from the connection socket;
For socket programming, the. NET Framework's socket class is the managed code version of the socket service provided by the Winsock32 API. There are a number of ways to implement network programming, and in most cases the Socket class method simply marshals the data to their native Win32 copy and handles any necessary security checks. If you are familiar with the Winsock API functions, it is very easy to write a network program with the socket class, and of course, if you have not touched it, it will not be too difficult to follow the following commentary, you will find that using the socket class to develop Windows network application is originally a rule to find, They follow roughly the same steps in most cases.

This section describes the use of sockets to implement a high-performance asynchronous UDP server, in fact, UDP is not divided between the client and the server, but we sometimes communicate with the server is using UDP to do.

Socket Asynchronous UDP Server

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net;using System.net.sockets;namespace netframe.net.udp.sock.asynchronous{//<summary>///Socket implementation Asynchronous UDP Server//&LT ;/summary> public class Asyncsocketudpserver {#region fields//<summary>//server program allowed        The maximum number of client connections//</summary> private int _maxclient;        <summary>///Current number of connected clients///</summary>//private int _clientcount;        <summary>///server using the sync socket///</summary> private socket _serversock; <summary>///client Session list///</summary>//private list<asyncudpsocketstate> _clien        Ts        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 socket UDP Server///</summary>/ <param name= "Listenport" > Listening ports </param> public asyncsocketudpserver (int listenport): this        (Ipaddress.any, listenport,1024) {}///<summary>//Asynchronous socket UDP Server///</summary>//<param name= "Lo Calep "> Monitoring endpoint </param> public asyncsocketudpserver (IPEndPoint localEP): This (localep.address, l Ocalep.port,1024) {}///<summary>///asynchronous Socket 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 asyncsocketudpserver (IPAddress localipaddres s, int listenport, int maxclient) {this.            Address = localipaddress; This.            Port = Listenport; This.            Encoding = Encoding.default;            _maxclient = maxclient;            _clients = new list<asyncudpsocketstate> ();            _serversock = new Socket (localipaddress.addressfamily, Sockettype.dgram, PROTOCOLTYPE.UDP);        _recvbuffer=new Byte[_serversock.receivebuffersize]; } #endregion #region Method///<summary>///Start server//</summary>/      <returns> Asynchronous TCP Server </returns> public void Start ()  {if (!                isrunning) {isrunning = true; _serversock.bind (New IPEndPoint (this. Address, this.                Port));                _serversock.connect (New IPEndPoint (Ipaddress.any, 0));                Asyncsocketudpstate so = new Asyncsocketudpstate ();                So.worksocket = _serversock; _serversock.beginreceivefrom (so.buffer, 0, so.buffer.Length, Socketflags.none, ref so.remote, new Async                Callback (Receivedataasync), null);                EndPoint sender = new IPEndPoint (ipaddress.any, 0); _serversock.beginreceivefrom (_recvbuffer, 0, _recvbuffer.length, socketflags.none,//ref sender, New                AsyncCallback (Receivedataasync), sender); What is the difference between BeginReceive and Beginreceivefrom/*_serversock.beginreceive (_recvbuffer, 0, _recvbuffer.length, Sock Etflags.none, New AsyncCallback (Receivedataasync), NULL); */}}/<summary>///Stop server///</summary> public void Stop () {if (isrunnin                g) {isrunning = false;                _serversock.close ();        TODO closes the connection to all clients}}///<summary>//////For receiving data//</summary> <param name= "ar" ></param> private void Receivedataasync (IAsyncResult ar) {Asyncs Ocketudpstate so = ar.            AsyncState as Asyncsocketudpstate;            EndPoint sender = new IPEndPoint (ipaddress.any, 0);            int len =-1;                try {len = _serversock.endreceivefrom (AR, ref so.remote);                len = _serversock.endreceivefrom (AR, ref sender);                Endreceivefrom and EndReceive difference//len = _serversock.endreceive (AR);            TODO processing data//triggering data received event raisedatareceived (so); } catch (ExcEption) {//todo handles exception raiseotherexception (so); } finally {if (isrunning && _serversock! = null) _servers Ock. Beginreceivefrom (so.buffer, 0, so.buffer.Length, Socketflags.none, ref so.remote, new AsyncCallback (Receive            Dataasync), so); }}///<summary>/////</summary>//<param name= "MSG" ></        param>//<param name= "remote" ></param> public void Send (String msg,endpoint remote)            {byte[] data = Encoding.Default.GetBytes (msg);                try {raisepreparesend (null); _serversock.beginsendto (data, 0, data.            Length, Socketflags.none, remote, new AsyncCallback (Senddataend), _serversock); } catch (Exception) {//todo exception handling raiseotherexception (NULL); }} private void Senddataend (IAsyncResult ar) {(Socket) ar. asyncstate).            Endsendto (AR);        Raisecompletedsend (NULL); } #endregion #region Events///<summary>///Receive data events///</summary> Pub        Lic event eventhandler<asyncsocketudpeventargs> datareceived;                private void raisedatareceived (Asyncsocketudpstate state) {if (datareceived! = null) {            DataReceived (This, new Asyncsocketudpeventargs (state)); }}///<summary>///events before sending data///</summary> public event eventhandler<        Asyncsocketudpeventargs> Preparesend;        <summary>///trigger event before data is sent///</summary>//<param name= "state" ></param>               private void Raisepreparesend (Asyncsocketudpstate state) {if (preparesend! = null) { Preparesend (This, new Asyncsocketudpeventargs (state)); }}///<summary>///Data Send complete Event///</summary> public event eventhandler<        Asyncsocketudpeventargs> Completedsend;         <summary>///Trigger data sent events///</summary>//<param name= "state" ></param>            private void Raisecompletedsend (Asyncsocketudpstate state) {if (completedsend! = null)            {Completedsend (this, new Asyncsocketudpeventargs (state)); }}///<summary>//Network error events///</summary> public event Eventhandler<as        Yncsocketudpeventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param>                private void Raiseneterror (Asyncsocketudpstate state) {if (neterror! = null) { Neterror (This, New Asyncsocketudpeventargs (state)); }}///<summary>///exception Event///</summary> public event Eventhandler<asyn        Csocketudpeventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param> private void Raiseotherexception (asyncsocketudpstate state, String descrip) {if (otherexception! = N            ull) {otherexception (this, new Asyncsocketudpeventargs (Descrip, state)); }} private void Raiseotherexception (Asyncsocketudpstate state) {raiseotherexception (stat        E, "");        #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 (asyncsocketudpstate state) {if (state! = null) {               _clients.                Remove (state);                _clientcount--; TODO triggers Shutdown Event}}///<summary>///Close all client sessions, and all client connections will be disconnected///</summary&        Gt            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//bothmanaged 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 (_serversock! = null) {_serversock = null;                        }} catch (SocketException) {//todo                    Raiseotherexception (NULL);            }} disposed = true; }} #endregion}}

Session Encapsulation Class

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net;using System.net.sockets;namespace netframe.net.udp.sock.asynchronous{public    class Asyncsocketudpstate    {        / /Client   socket.        Public Socket worksocket = 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 EndPoint remote = new IPEndPoint (ipaddress.any, 0);}    }
Socket asynchronous UDP Server event parameter class

Using system;using system.collections.generic;using system.linq;using system.text;namespace  netframe.net.udp.sock.asynchronous{//<summary>///SOCKET Asynchronous UDP event class///</summary> public class Asyncsocketudpeventargs:eventargs {///<summary>////</summary> PU        Blic string _msg;        <summary>///Client Status Package class////</summary> public asyncsocketudpstate _state;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Asyncsocketudpeventargs (String msg) {this._msg = msg;        ishandled = false;            Public Asyncsocketudpeventargs (asyncsocketudpstate state) {this._state = state;        ishandled = false;            } public Asyncsocketudpeventargs (String msg, asyncsocketudpstate state) {this._msg = msg; This._state = STate        ishandled = false; }    }}

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



C # Network Programming series article (v) Socket implementation asynchronous UDP server

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.