C # Network Programming series article (vi) Socket implementation synchronous UDP server

Source: Internet
Author: User

This article describes

In. 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 using a socket to implement a synchronous UDP server.

Socket Synchronization 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.sock.synchronous{///<summary>//Socket for synchronous UD        P Server///</summary> public class Socketudpserver {#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 using the sync socket///</summary> private socket _serversock;        <summary>///client Session list///</summary> private list<socketudpstate> _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>//Asynchronous socket UDP Server///</summary>/ <param name= "listenport" > Monitored ports </param> public socketudpserver (int listenport): This (IPAd Dress.        Any, listenport,1024) {}//<summary>///Async socket UDP server///</summary>  <param name= "localEP" > Monitoring endpoint </param> public socketudpserver (IPEndPoint localEP): This (localep.address, localEp. port,1024) {}///<summary>///Async 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 socketudpserver (IPAddress localipaddress, int li Stenport, int maxclient) {this.            Address = localipaddress; This.            Port = Listenport; This.            Encoding = Encoding.default;            _maxclient = maxclient;            _clients = new list<socketudpstate> ();            _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)); Initiates a thread listener data new Thread (Receivedata).            Start ();            }}///<summary>//Stop server///</summary> public void Stop () {                if (isrunning) {isrunning = false;                _serversock.close ();            TODO closes the connection to all clients closeallclient ();        }}///<summary>///Synchronous Data Reception method///</summary> private void Receivedata ()            {int len =-1;            EndPoint remote = NULL; while (true) {try {len = _serversock.receivefrom (_recvbuffer                    , ref remote); if (!_clients. Contains (remote))//{//_clients.           ADD (remote);         }} catch (Exception) {//todo exception handling operation                Raiseotherexception (NULL); }}}///<summary>///////</summary> public void Send (s            Tring msg, EndPoint clientip) {byte[] data = Encoding.Default.GetBytes (msg);                try {_serversock.sendto (data, clientip);            Data Send completion event raisecompletedsend (NULL);            } catch (Exception) {//todo exception handling raiseotherexception (NULL); }} #endregion Events #region///<summary>///</summary&gt        ;        public event eventhandler<socketudpeventargs> DataReceived;               private void raisedatareceived (Socketudpstate state) {if (datareceived! = null) { DataReceived (This, new Socketudpeventargs (state)); }}///<summary>///Data Send complete Event///</summary> public event eventhandler<        Socketudpeventargs> Completedsend;         <summary>///Trigger data sent events///</summary>//<param name= "state" ></param>                private void Raisecompletedsend (Socketudpstate state) {if (completedsend! = null) {            Completedsend (This, new Socketudpeventargs (state)); }}///<summary>//Network error events///</summary> public event Eventhandler<so        Cketudpeventargs> Neterror;        <summary>///Trigger Network error events///</summary>//<param name= "state" ></param>                private void Raiseneterror (Socketudpstate state) {if (neterror! = null) { Neterror (This, new Socketudpeventargs (state)); }}///<summary>///exception Event///</summary> public event Eventhandler<sock        Etudpeventargs> otherexception;        <summary>///Trigger Exception events///</summary>//<param name= "state" ></param>            private void Raiseotherexception (socketudpstate state, String descrip) {if (otherexception! = null)            {Otherexception (this, new Socketudpeventargs (Descrip, state)); }} private void Raiseotherexception (Socketudpstate 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 (Socketudpstate 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 (Socketudpstate 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 Dispose (bool disposing) {if (!th                        is.disposed) {if (disposing) {try {                        Stop ();                        if (_serversock! = null) {_serversock = null;                        }} catch (SocketException) {//todo                    Raiseotherexception (NULL);            }} disposed = true; }} #endregion}}

Customer Status 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.sock.synchronous{public    class Socketudpstate    {        //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);}    }


Server Event Parameter class

Using system;using system.collections.generic;using system.linq;using system.text;namespace netframe.net.udp.sock.synchronous{//<summary>///Socket Implementation Synchronous UDP Server///</summary> public class Socketudpeventargs:eventargs {//<summary>////</summary> public str        ing _msg;        <summary>///Client Status Package class////</summary> public socketudpstate _state;        <summary>///whether the///</summary> public bool ishandled {get; set;}            Public Socketudpeventargs (String msg) {this._msg = msg;        ishandled = false;            Public Socketudpeventargs (socketudpstate state) {this._state = state;        ishandled = false;            } public Socketudpeventargs (String msg, socketudpstate state) {this._msg = msg;            This._state = State;   ishandled = false;     }    }} 

The above is the C # network programming series (vi) socket implementation of the content of the 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.