C # Network Programming series article (iii) TcpListener implementing an asynchronous TCP server

Source: Internet
Author: User
Tags getstream

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 TcpListener class provides some simple methods for listening and accepting incoming connection requests in blocking synchronous mode. You can use the TcpClient or Socket to connect the TcpListener. You can use IPEndPoint, local IP addresses and port numbers, or use only port numbers to create TcpListener. You can specify the local IP address as any, specifying the local port number as 0 if you want the underlying service provider to assign these values to you. If you choose to do this, you can use the Localendpoint property after you connect the socket to identify the information that you have specified. Using the Start method, you can start listening for incoming connection requests. Start queues the incoming connection until you call the Stop method or it has finished maxconnections queued. You can use AcceptSocket or accepttcpclient to extract connections from incoming connection request queues. Both of these methods will block. If you want to avoid blocking, you can first use the Pending method to determine whether a connection request is available in the queue.

Although the TcpListener has been packaged relatively good, we use it in the construction of a relatively good asynchronous TCP server, here is still the same as the first two chapters, give the server code, the code is very detailed comments, I will also give the relevant encapsulation class.

TcpListener asynchronous TCP Server server code
Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets;using System.net;namespace netframe.net.tcp.listener.asynchronous{//<summary>//TcpListener Implementing an Asynchronous TCP Server///&L T;/summary> public class Asynctcpserver:idisposable {#region//<summary>/        Maximum number of client connections allowed by the server program//</summary> private int _maxclient;        <summary>///Current number of connections///</summary> private int _clientcount;        <summary>///server uses asynchronous TcpListener///</summary> private TcpListener _listener;        <summary>///client Session list///</summary> private list<object> _clients;        private bool disposed = false; #endregion #region Properties//<summary>//Whether the server is running///</summary> PU    blic 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 TCP Servers///</summary>// <param name= "listenport" > Monitored ports </param> public asynctcpserver (int listenport): This (ipaddres  S.any, Listenport) {}//<summary>///Asynchronous TCP Server///</summary>// <param name= "localEP" > Monitoring endpoint </param> public asynctcpserver (IPEndPoint localEP): This (local Ep.        Address, Localep.port) {}//<summary>//Asynchronous TCP Server///</summary> <param Name= "LoCalipaddress "> Listening IP address </param>//<param name=" Listenport "> Listening ports </param> public ASYNCTC            PServer (IPAddress localipaddress, int listenport) {Address = localipaddress;            Port = Listenport; This.            Encoding = Encoding.default;            _clients = new list<object> ();            _listener = new TcpListener (Address, Port); _listener.        Allownattraversal (TRUE); } #endregion #region Method///<summary>///Start server//</summary> p ublic void Start () {if (!                isrunning) {isrunning = true; _listener.                Start (); _listener.            Beginaccepttcpclient (New AsyncCallback (handletcpclientaccepted), _listener);         }}///<summary>//Start server///</summary>//<param name= "Backlog" > Maximum length of the pending connection sequence allowed by the server// </param> public void Start (int backlog) {if (!                isrunning) {isrunning = true; _listener.                Start (backlog); _listener.            Beginaccepttcpclient (New AsyncCallback (handletcpclientaccepted), _listener);            }}///<summary>//Stop server///</summary> public void Stop () {                if (isrunning) {isrunning = false; _listener.                Stop ();                Lock (_clients) {//Close all client connections closeallclient (); }}}///<summary>///For handling client connections///</summary>//<param Name= "AR" ></param> private void handletcpclientaccepted (IAsyncResult ar) {if (isrunning ) {//tcplistener TcpListener = (tcplistener) ar.        asyncstate;        TcpClient client = _listener.                Endaccepttcpclient (AR); byte[] buffer = new byte[client.                Receivebuffersize];                Tcpclientstate state = new Tcpclientstate (client, buffer); Lock (_clients) {_clients.                    ADD (state);                Raiseclientconnected (state);                } NetworkStream stream = State.networkstream; Begins an asynchronous read of the data stream. BeginRead (state. Buffer, 0, state.                Buffer.length, handledatareceived, state); _listener. Beginaccepttcpclient (New AsyncCallback (handletcpclientaccepted), AR.            asyncstate); }}///<summary>//Data Accept callback function///</summary>//<param name= "AR" >&l                t;/param> private void handledatareceived (IAsyncResult ar) {if (isrunning) { Tcpclientstate state = (tcpclientstate) ar.   asyncstate;             NetworkStream stream = State.networkstream;                int recv = 0; try {recv = stream.                EndRead (AR);                } catch {recv = 0; } if (recv = = 0) {//connection has been closed lock                    (_clients) {_clients.                        Remove (state);                        Trigger Client Connection Disconnect event raiseclientdisconnected (state);                    Return }}//received Byte and trigger event notification byte[] buff = new Byte[re                CV]; Buffer.blockcopy (state.                Buffer, 0, buff, 0, recv);                Trigger data received event raisedatareceived (state); Continue listening for TCP datagram packets stream. BeginRead (state. Buffer, 0, state. Buffer.length, Handledatareceived, state); }}////<summary>////</summary>//<param name= "state" > Received number  Client session </param>//<param name= "Data" > Datagram </param> public void Send (Tcpclientstate state,            Byte[] data) {raisepreparesend (state); Send (state.        TcpClient, data); }///<summary>///asynchronously sends data to the specified client///</summary>//<param name= "Client" > Customer End </param>//<param name= "Data" > Messages </param> public void Send (TcpClient client, byte[] Data ) {if (!            isrunning) throw new InvalidProgramException ("This TCP Scoket server have not been started.");            if (client = = null) throw new ArgumentNullException ("Client");            if (data = null) throw new ArgumentNullException ("Data"); Client. GetStream (). BeginWrite (data, 0, data. LEngth, senddataend, client); }///<summary>///Send data completion processing function///</summary>//<param name= "AR" > Target client sock et</param> private void Senddataend (IAsyncResult ar) {(TcpClient) ar. asyncstate). GetStream ().            EndWrite (AR);        Raisecompletedsend (NULL);        } #endregion #region Event///<summary>///connection to client established event///</summary>        public event eventhandler<asynceventargs> clientconnected; <summary>//connection to client disconnected Event///</summary> public event Eventhandler<asynceventargs        > clientdisconnected;        <summary>///Trigger Client Connection Events///</summary>//<param name= "state" ></param>            private void raiseclientconnected (Tcpclientstate state) {if (clientconnected! = null) {clientconnected (this, new Asynceventargs (state)); }}///<summary>//Trigger Client Connection Disconnect Event///</summary>//<param name= "client "></param> private void raiseclientdisconnected (Tcpclientstate state) {if (Clientdiscon            Nected! = null) {clientdisconnected (this, new Asynceventargs ("disconnection")); }}///<summary> Receive data events///</summary> public event Eventhandler<a        Synceventargs> datareceived;                private void raisedatareceived (Tcpclientstate state) {if (datareceived! = null) {            DataReceived (This, new Asynceventargs (state)); }}///<summary>///events before sending data///</summary> public event eventhandler<        Asynceventargs> Preparesend;      <summary>///trigger event before data is sent///</summary>//<param name= "state" ></param>  private void Raisepreparesend (Tcpclientstate state) {if (preparesend! = null) {            Preparesend (This, new Asynceventargs (state)); }}///<summary>///Data Send complete Event///</summary> public event eventhandler<        Asynceventargs> Completedsend;         <summary>///Trigger data sent events///</summary>//<param name= "state" ></param>                private void Raisecompletedsend (Tcpclientstate state) {if (completedsend! = null) {            Completedsend (This, new Asynceventargs (state)); }}///<summary>//Network error events///</summary> public event Eventhandler<as        Ynceventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param>    private void Raiseneterror (Tcpclientstate state)    {if (neterror! = null) {Neterror (this, new Asynceventargs (state)); }}///<summary>///exception Event///</summary> public event Eventhandler<asyn        Ceventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param>            private void Raiseotherexception (tcpclientstate state, String descrip) {if (otherexception! = null)            {Otherexception (this, new Asynceventargs (Descrip, state)); }} private void Raiseotherexception (Tcpclientstate 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 (Tcpclientstate state) {      if (state = null) {state.                Close (); _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 (Tcpclientstate client in _clients) {C            Lose (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 (_listener! = null) {_listener = null;                        }} catch (SocketException) {//todo                    Raiseotherexception (NULL);            }} disposed = true; }} #endregion}}
Client processing wrapper class
Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets; Namespace netframe.net.tcp.listener.asynchronous{public class Tcpclientstate {//<summary>//        /client-related TcpClient//</summary> public TcpClient TcpClient {get; private set;}        <summary>///Get buffer//</summary> public byte[] buffer {get; private set;}            <summary>///Get network streaming///</summary> public NetworkStream NetworkStream {        get {return Tcpclient.getstream ();}                } public Tcpclientstate (TcpClient TcpClient, byte[] buffer) {if (TcpClient = = null)            throw new ArgumentNullException ("TcpClient");            if (buffer = = null) throw new ArgumentNullException ("buffer"); This.            TcpClient = TcpClient; This.        buffer = buffer; }//<summary>        Close//</summary> public void Close () {//Closed data accept and send Tcpclien            T.close ();        Buffer = null; }    }}
Server Event Parameter class
Using system;using system.collections.generic;using system.linq;using system.text;namespace    netframe.net.tcp.listener.asynchronous{//<summary>///asynchronous TcpListener TCP Server Event parameter class///</summary>        public class Asynceventargs:eventargs {///<summary>/////</summary>        public string _msg;        <summary>///Client Status Package class////</summary> public tcpclientstate _state;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Asynceventargs (String msg) {this._msg = msg;        ishandled = false;            Public Asynceventargs (tcpclientstate state) {this._state = state;        ishandled = false;            } public Asynceventargs (String msg, tcpclientstate 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 (iii) TcpListener implementing an asynchronous TCP 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.