C # Network Programming series article (iv) TcpListener implementation of synchronous TCP server

Source: Internet
Author: User
Tags getstream

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 synchronous 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 Synchronizing a TCP 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.tcp.listener.synchronous{//<summary>//TcpListen        ER implementation Synchronous TCP server//</summary> public class TCPServer {#region fields//<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<tcpclienthandle> _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 Constructor///<summary>///Synchronous TCP Server///</summary>//&L T;param name= "listenport" > Monitored ports </param> public tcpserver (int listenport): This (Ipaddress.any, Listenport, 1024x768) {}//<summary>///Sync TCP server///</summary>// <param name= "localEP" > Monitoring endpoint </param> public tcpserver (IPEndPoint localEP): This (localep.add        Ress, Localep.port, 1024x768) {}//<summary>///Synchronous TCP Server//</summary> <pAram Name= "localipaddress" > IP address of the listener </param>//<param name= "listenport" > Monitored ports </param>/ <param name= "maxclient" > Maximum number of clients </param> public tcpserver (IPAddress localipaddress, int listenport, I NT Maxclient) {this.            Address = localipaddress; This.            Port = Listenport; This.            Encoding = Encoding.default;            _maxclient = maxclient;            _clients = new list<tcpclienthandle> (); _listener = new TcpListener (new IPEndPoint (this. Address, this.        Port)); } #endregion #region Method///<summary>///Start server//</summary> p ublic void Start () {if (!                isrunning) {isrunning = true; _listener.                Start ();                Thread thread = new Thread (Accept); Thread.            Start (); }}///<summary>//Start monitoring///&LT;/SUMMARY&GT            private void Accept () {tcpclienthandle handle; while (isrunning) {TcpClient client = _listener.                AcceptTcpClient ();                if (_clientcount >= _maxclient) {//todo trigger event} else                    {handle = new Tcpclienthandle (client);                    _clientcount++; _clients.                    ADD (handle); TODO creates a thread that processes the client and starts//uses the thread pool to manipulate the new thread (new ThreadStart (handle. Receviedata)).                Start ();        }}}///<summary>//Stop server///</summary> public void Stop ()                {if (isrunning) {isrunning = false; _listener.                Stop ();        TODO closes the connection to all clients}}///<summary>/////</summary>public void Send (string msg, TcpClient client) {//todo} #endregion #region Event <summary>///Client connection established Event///</summary> public event Eventhandler<tcpeventar        Gs> clientconnected; <summary>//connection to client disconnected Event///</summary> public event EVENTHANDLER&LT;TCPEVENTARGS&G T        clientdisconnected;        <summary>///Trigger Client Connection Events///</summary>//<param name= "state" ></param>            private void raiseclientconnected (Tcpclienthandle handle) {if (clientconnected! = null)            {clientconnected (this, new Tcpeventargs (handle)); }}///<summary>//Trigger Client Connection Disconnect Event///</summary>//<param name= "client "></param> private void raiseclientdisconnected (Socket client) {if (clientdisconnected ! = nulL) {clientdisconnected (this, new Tcpeventargs ("disconnection")); }}///<summary> Receive data events///</summary> public event Eventhandler<t        Cpeventargs> datareceived;                private void raisedatareceived (Tcpclienthandle handle) {if (datareceived! = null) {            DataReceived (This, new Tcpeventargs (handle)); }}///<summary>//Data Send Event///</summary> public event EVENTHANDLER&LT;TC        Peventargs> Completedsend;        <summary>///Trigger data sending events///</summary>//<param name= "state" ></param>                private void Raisecompletedsend (Tcpclienthandle handle) {if (completedsend! = null) {            Completedsend (This, new Tcpeventargs (handle));   }}///<summary>//Network error events///</summary>     public event eventhandler<tcpeventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param>                private void Raiseneterror (Tcpclienthandle handle) {if (neterror! = null) {            Neterror (This, new Tcpeventargs (handle)); }}///<summary>///exception Event///</summary> public event EVENTHANDLER&LT;TCPE        Ventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param> private void Raiseotherexception (Tcpclienthandle handle, String descrip) {if (otherexception! = null            {Otherexception (this, new Tcpeventargs (Descrip, handle));  }} private void Raiseotherexception (Tcpclienthandle handle) {raiseotherexception (handle,    "");    #endregion #region Close//<summary>//Close a session with the client///&LT;/SUMMARY&G        T            <param name= "Handle" > Client session object that needs to be closed </param> public void close (Tcpclienthandle handle) { if (handle! = NULL) {_clients.                Remove (handle); Handle.                Dispose ();                _clientcount--; TODO triggers Shutdown Event}}///<summary>///Close all client sessions, and all client connections will be disconnected///</summary&        Gt                public void Closeallclient () {foreach (Tcpclienthandle handle in _clients) {            Close (handle);            } _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 exception            }} disposed = true;   }     } #endregion}} 

Client processing wrapper classes

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets;using    System.io;namespace netframe.net.tcp.listener.synchronous{//<summary>///TcpListener Client Connection processing class for synchronizing TCP servers        </summary> public class Tcpclienthandle {private TcpClient _tcpclient;        Private BinaryReader RS;        Private BinaryWriter ws;        <summary>///ID is connected to client///</summary> private bool _is_connect;            public bool Isconnect {get {return _is_connect;}        set {_is_connect = value;}        }///<summary>//Data Accept buffer///</summary> private byte[] _recvbuffer;            Public Tcpclienthandle (TcpClient client) {_tcpclient = client; rs = new BinaryReader (client.            GetStream ()); WS = New BinaryWriter (client.            GetStream ());   NetworkStream ns = Tmptcpclient.getstream ();         if (ns. Canread&&ns. CanWrite) _recvbuffer=new byte[client.        Receivebuffersize];            }///<summary>///Receive data///</summary> public void Receviedata () {            int len = 0; while (_is_connect) {try {len = rs.                Read (_recvbuffer, 0, _recvbuffer.length);                } catch (Exception) {break;                    } if (len = = 0) {//the client has disconnected from server                Break        }//todo processing received data}}///<summary>//Send data to Client            </summary>//<param name= "msg" ></param> public void SendData (String msg) {            byte[] data = Encoding.Default.GetBytes (msg);           try {     Ws. Write (data, 0, data.                Length); Ws.            Flush (); } catch (Exception) {//todo handling exception}} #region event//to        Do message send event//todo data receive event//todo exception handling event #endregion #region Release//<summary>        Performs application-defined tasks associated with freeing,///releasing, or resetting unmanaged resources.            </summary> public void Dispose () {_is_connect = false; if (_tcpclient! = null) {_tcpclient.                Close ();            _tcpclient = null; } GC.        SuppressFinalize (this); } #endregion}}


TCP Server Event parameter class

Using system;using system.collections.generic;using system.linq;using system.text;namespace netframe.net.tcp.listener.synchronous{//<summary>///Synchronous TcpListener TCP Server event class///</summary> PU Blic class Tcpeventargs:eventargs {///<summary>////</summary> Pub        Lic string _msg;        <summary>///Client Status Package class////</summary> public tcpclienthandle _handle;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Tcpeventargs (String msg) {this._msg = msg;        ishandled = false;            } public Tcpeventargs (Tcpclienthandle handle) {this._handle = handle;        ishandled = false;            } public Tcpeventargs (String msg, Tcpclienthandle handle) {this._msg = msg;            This._handle = handle;    ishandled = false;    }    }} 

The above is the C # network programming series (iv) TcpListener implementation of the content of the synchronization TCP 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.