C # Network Programming series article (ii) Socket implementation synchronous TCP Server

Source: Internet
Author: User

This article describes

As I said in the previous blog post, I will introduce the use of sockets and TcpListener and UdpClient in C # to implement various synchronous and asynchronous TCP and UDP servers, all of which I spent a lot of days summing up, believing that I was just in touch with C # Network programming friends will not be as I used to find information everywhere, debugging everywhere. This time I introduce a synchronous TCP server using a socket, the difference between a synchronous TCP server and the asynchronous TCP server described in the first one is whether the socket will block when it calls accept.

Synchronous TCP Server in the acceptance of a client's request is generally open a thread to handle and the client's communication work, this way the bad place is the resource consumption, but if the use of a thread pool, the allocation of a certain number of threads in advance, performance is still possible.

But I give a lot of ways to implement the server, the main purpose is to test which situation performance is good, for the moment, the asynchronous mode is relatively nice, but in fact there is a IOCP mode performance is the best ...

Socket Synchronization TCP Server

Service-side code

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.sock.synchronous{///<summary>//socket-based synchronization        TCP Server///</summary> public class Sockettcpserver {#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 use asynchronous socket///</summary> private socket _serversock;         <summary>///client Session list///</summary> private list<socketclienthandle> _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>///sync Socket TCP Server///</summary> <param name= "listenport" > Monitored ports </param> public sockettcpserver (int listenport): This (I Paddress.any, Listenport, 1024x768) {}//<summary>///sync Socket TCP Server//&LT;/SU            mmary>//<param name= "localep" > Monitored endpoints </param> public sockettcpserver (IPEndPoint localEP) : This (localep.address, Localep.port, 1024x768) {}//<summary>///Sync Socket TCP Service Service///</summary>//<param name= "localipaddress" > Listening IP address </param>//<param name= "Listenport" ; listening ports </param>//<param name= "Maxclient" > Max clients </param> public Sockettcpserver (ipaddres s localipaddress, int listenport, int maxclient) {this.            Address = localipaddress; This.            Port = Listenport; This.            Encoding = Encoding.default;            _maxclient = maxclient;            _clients = new list<socketclienthandle> ();        _serversock = new Socket (localipaddress.addressfamily, SocketType.Stream, protocoltype.tcp); } #endregion #region Method///<summary>///Start server//</summary> p ublic void Start () {if (!                isrunning) {isrunning = true; _serversock.bind (New IPEndPoint (this. Address, this.                Port));                Thread thread = new Thread (Startlisten); ThRead.            Start ();        }}///<summary>///Start monitoring///</summary> private void Startlisten ()            {_serversock.listen (1024);            Socketclienthandle handle; while (isrunning) {if (_clientcount >= _maxclient) {//tod                O client Too much exception raiseotherexception (null);                    } else {Socket clientsock = _serversock.accept ();                    _clientcount++;                    TODO creates a thread that processes the client and starts handle = new Socketclienthandle (clientsock); _clients.                    ADD (handle); Use the thread pool to manipulate ThreadPool.QueueUserWorkItem (new WaitCallback (handle.                    Receviedata));                    Thread pthread; Pthread = new Thread (new ThreadStart (client).                    Receviedata)); Pthread.                Start ();    This should be done using line pool}}}///<summary>//Stop server//</summ                ary> public void Stop () {if (isrunning) {isrunning = false;                _serversock.close (); TODO closes the connection to all clients}}///<summary>//////</summary> Pub        LIC void Send (String msg, Socketclienthandle client) {//todo}//<summary> Close a session with clients///</summary>//<param name= "Handle" > Client session objects that need to be closed </param> pub LIC void Close (Socketclienthandle 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> public void Closeallclient () {foreach (Socketclienthandle handle in _clients)            {Close (handle);            } _clientcount = 0; _clients.        Clear ();        } #endregion #region Event///<summary>///connection to client established event///</summary>        public event eventhandler<socketeventargs> clientconnected; <summary>//connection to client disconnected Event///</summary> public event Eventhandler<socketeventarg        S> clientdisconnected;        <summary>///Trigger Client Connection Events///</summary>//<param name= "state" ></param>            private void raiseclientconnected (Socketclienthandle handle) {if (clientconnected! = null)            {clientconnected (this, new Socketeventargs (handle)); }}///<summary>//Trigger Client Connection Disconnect Event///</summary>//<param name= "client" ></param> private void raiseclientdisconnected (Socket client) {if (clientdisconnected! = null) {clientdisconnected (this, new Socketeventargs ("            Disconnected ")); }}///<summary> Receive data events///</summary> public event Eventhandler<s        Ocketeventargs> datareceived;                private void raisedatareceived (Socketclienthandle handle) {if (datareceived! = null) {            DataReceived (This, new Socketeventargs (handle)); }}///<summary>//Data Send Event///</summary> public event Eventhandler<so        Cketeventargs> Completedsend;        <summary>///Trigger data sending events///</summary>//<param name= "state" ></param> private void Raisecompletedsend (Socketclienthandle handle) {if (completedsEnd! = null) {Completedsend (this, new Socketeventargs (handle)); }}///<summary>//Network error events///</summary> public event Eventhandler<so        Cketeventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param>                private void Raiseneterror (Socketclienthandle handle) {if (neterror! = null) {            Neterror (This, new Socketeventargs (handle)); }}///<summary>///exception Event///</summary> public event Eventhandler<sock        Eteventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param> private void Raiseotherexception (Socketclienthandle handle, String descrip) {if (otherexception! = N            ull) {    Otherexception (This, new Socketeventargs (Descrip, handle)); }} private void Raiseotherexception (Socketclienthandle handle) {Raiseotherexception (hand        Le, ""); } #endregion #region Close not implemented #endregion #region released//<summary>//Per        Forms 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 (_serversock! = null) {_serversock = null;                    }} catch (SocketException) {//todo exception            }} disposed = true; }} #endregion}}

The handle class that


encapsulates for client operations

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Sockets; namespace netframe.net.tcp.sock.synchronous{//<summary>///Socket server handles client processing classes for Client connection encapsulation///</summar Y> public class Socketclienthandle:idisposable {//<summary>///client-associated socket//        </summary> private Socket _client;        <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 Socketclienthandle (Socket client) {this._client = client;            _is_connect = true;        _recvbuffer = new byte[1024 * 1024 * 2]; } #region Method///<summary>//Accept data from the client        </summary> public void Receviedata (Object state) {int len =-1; while (_is_connect) {try {len = _client.                Receive (_recvbuffer);        } catch (Exception) {//todo}}}            <summary>///Send data to client///</summary> public void SendData (String msg) {            byte[] data = Encoding.Default.GetBytes (msg); try {//have a better way of writing _client.            Send (data); } catch (Exception) {//todo handles exception}} #endregion #reg Ion event//todo Message Send event//todo data received event//todo exception handling event #endregion #region Release//<s Ummary>//performs application-defined tasks associated with freeing,///ReleaSing, or resetting unmanaged resources.            </summary> public void Dispose () {_is_connect = false; if (_client! = null) {_client.                Close ();            _client = null; } GC.        SuppressFinalize (this); } #endregion}}


The time parameter class for the socket synchronization TCP server

Using system;using system.collections.generic;using system.linq;using system.text;namespace netframe.net.tcp.sock.synchronous{//<summary>///Synchronous Socket TCP Server event class///</summary> public Clas s Socketeventargs:eventargs {///<summary>////</summary> Public St        Ring _msg;        <summary>///Client Status Package class////</summary> public socketclienthandle _handle;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Socketeventargs (String msg) {this._msg = msg;        ishandled = false;            } public Socketeventargs (Socketclienthandle handle) {this._handle = handle;        ishandled = false;            } public Socketeventargs (String msg, Socketclienthandle handle) {this._msg = msg;            This._handle = handle; Ishandled= false; }    }}

The above is the C # network programming series of articles (ii) of the socket to synchronize the contents of the 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.