C # network programming series Article (5) Socket Implement Asynchronous UDP server,

Source: Internet
Author: User

C # network programming series Article (5) Socket Implement Asynchronous UDP server,
Originality statement

Author: Xiaozhu zz this article address http://blog.csdn.net/zhujunxxxxx/article/details/44258719 reprint please indicate the source

Document Series directory

C # network programming series (I) Socket implementation asynchronous TCP Server

C # network programming series (ii) Socket implementation synchronous TCP Server

C # network programming series Article 3 TcpListener asynchronous TCP Server

C # network programming series (4) TcpListener for Synchronous TCP Server

C # network programming series (v) Socket implementation asynchronous UDP Server

C # network programming series Article 6 Socket synchronous UDP Server

C # network programming Article 7 UdpClient Implement Asynchronous UDP Server

C # network programming series (8) UdpClient for Synchronous UDP Server

In. Net, the System. Net. Sockets namespace provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to strictly control network access. System. all other network protocol classes in the. Net namespace are built on the Socket implementation. For example, TCPClient, TCPListener, and UDPClient encapsulate detailed information about TCP and UDP connections created to the Internet; the NetworkStream class provides basic data streams for network access. Many common Internet services can see Socket traces, such as Telnet, Http, Email, and Echo, despite the different definitions of the communication Protocol, the basic transmission of these services uses sockets. In fact, the Socket can be considered as a data channel like a Stream. This channel is set up between the application end (client) and the remote server end, and then reads (receives) data) and write (send) for this channel.
It can be seen that after a Socket object is created on the application or server, you can use the Send/SentTo method to Send data to the connected Socket, alternatively, use the Receive/ReceiveFrom method to Receive data from the connected Socket;
For Socket programming, the Socket class of the. NET Framework is the managed code version of the Socket service provided by the Winsock32 API. A large number of methods are provided for network programming. In most cases, the Socket class method only sends data to their local Win32 copies and handles any necessary security checks. If you are familiar with Winsock API functions, it will be very easy to write network programs using the Socket class. Of course, if you have never been in touch with it, it will not be too difficult. Follow the instructions below, you will find that there are rules to develop windows network applications using the Socket class, which follow roughly the same steps in most cases.

This section describes how to use Socket to implement a high-performance asynchronous UDP server. In fact, UDP does not distinguish between clients and servers, but sometimes we use UDP to communicate with servers.

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 implements Asynchronous UDP server // </summary> public class AsyncSocketUDPServer {# region Fields // <summary> // server maximum number of client connections allowed by the program /// </summary> private int _ maxClient; /// <summary> /// number of clients currently connected /// </summary> // private in T _ clientCount; // <summary> // synchronous socket used by the server /// </summary> private Socket _ serverSock; /// <summary> /// Client Session List /// </summary> // private List <AsyncUDPSocketState> _ clients; private bool disposed = false; /// <summary> /// data accept buffer /// </summary> private byte [] _ recvBuffer; # endregion # region Properties // <summary> // whether the server is running // </summary> public bool IsRunning {get; private set ;}/// <Summary> /// IP Address of the listener /// </summary> public IPAddress Address {get; private set ;} /// <summary> /// listener Port /// </summary> public int Port {get; private set ;} /// <summary> // Encoding used for communication /// </summary> public Encoding {get; set ;} # endregion # region constructor // <summary> // asynchronous Socket UDP server // </summary> /// <param name = "listenPort"> listener Port </param> public AsyncSocketUDPServer (int listenPort): This (IPAddress. any, listenPort, 1024) {}/// <summary> /// asynchronous Socket UDP server /// </summary> /// <param name = "localEP"> listener endpoint </param> public AsyncSocketUDPServer (IPEndPoint localEP): this (localEP. address, localEP. port, 1024) {}/// <summary> /// asynchronous Socket UDP server /// </summary> /// <param name = "localIPAddress"> IP address of the listener </param> /// <param name = "listenPort"> listening port </param> /// <param name = "maxClient"> maximum Number of clients </param> public AsyncSocketUDPServer (IPAddress localIPAddress, 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. receiveBufferSi Ze];} # endregion # region Method // <summary> // Start the 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 AsyncCallback (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, SocketFlags. none, new AsyncCallback (ReceiveDataAsync), null); * //} // <summary> // Stop the server // </summary> public void Stop () {if (IsRunning) {IsRunning = false; _ serverSock. close (); // TODO close the connection to all clients }/// <summary> /// Method for receiving data /// </summary> /// <param name = "ar "> </param> private void ReceiveDataAsync (IAsyncResult ar) {AsyncSocketUDPState so = ar. asyncState as AsyncSocketUDPState; // EndPoint sender = new IPEndPoint (IPAddress. any, 0); int len =-1; try {len = _ serverSock. endReceiveFrom (ar, ref so. remote); // len = _ serve RSock. endReceiveFrom (ar, ref sender); // difference between EndReceiveFrom and EndReceive // len = _ serverSock. endReceive (ar); // TODO processing data // triggers the data receipt event RaiseDataReceived (so);} catch (Exception) {// TODO processing Exception RaiseOtherException (so );} finally {if (IsRunning & _ serverSock! = Null) _ serverSock. beginReceiveFrom (so. buffer, 0, so. buffer. length, SocketFlags. none, ref so. remote, new AsyncCallback (ReceiveDataAsync), so );}} /// <summary> /// send data /// </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 (dat A, 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 event // <summary> // receives a data event // </summary> public event EventHandler <AsyncSocketUDPEventArgs> DataReceived; priva Te void RaiseDataReceived (AsyncSocketUDPState state) {if (DataReceived! = Null) {DataReceived (this, new AsyncSocketUDPEventArgs (state ));}} /// <summary> /// event before data sending /// </summary> public event EventHandler <AsyncSocketUDPEventArgs> PrepareSend; /// <summary> /// trigger the event before data sending /// </summary> /// <param name = "state"> </param> private void RaisePrepareSend (AsyncSocketUDPState state) {if (PrepareSend! = Null) {PrepareSend (this, new AsyncSocketUDPEventArgs (state ));}} /// <summary> /// data sending completion event /// </summary> public event EventHandler <AsyncSocketUDPEventArgs> CompletedSend; /// <summary> /// trigger the event of data sending completion /// </summary> /// <param name = "state"> </param> private void RaiseCompletedSend (AsyncSocketUDPState state) {if (CompletedSend! = Null) {CompletedSend (this, new AsyncSocketUDPEventArgs (state ));}} /// <summary> // network error event // </summary> public event EventHandler <AsyncSocketUDPEventArgs> NetError; /// <summary> /// trigger a network error event /// </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 <AsyncSocketUDPEventArgs> OtherException; /// <summary> /// trigger an exception event /// </summary> /// <param name = "state"> </param> private void RaiseOtherException (AsyncSocketUDPState state, string descrip) {if (OtherException! = Null) {OtherException (this, new AsyncSocketUDPEventArgs (descrip, state) ;}} private void RaiseOtherException (AsyncSocketUDPState state) {RaiseOtherException (state ,"");} # endregion # region Close /// <summary> // Close a session with the client /// </summary> /// <param name = "state"> required closed Client Session Object </param> public void Close (AsyncSocketUDPState state) {if (state! = Null) {// _ clients. remove (state); // _ clientCount --; // TODO triggers the Close event }}/// <summary> /// close all client sessions, connection to all clients will be disconnected /// </summary> 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 rese Specified unmanaged resources. /// </summary> public void Dispose () {Dispose (true); GC. suppressFinalize (this );} /// <summary> /// Releases unmanaged and-optionally-managed resources // </summary> /// <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 (! This. disposed) {if (disposing) {try {Stop (); if (_ serverSock! = Null) {_ serverSock = null;} catch (SocketException) {// TODO RaiseOtherException (null) ;}} disposed = true ;}# endregion }}

Session Encapsulation

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 = 1024;        // 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 parameters

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> /// message // </summary> public string _ msg; /// <summary> /// client status encapsulation class /// </summary> public AsyncSocketUDPState _ state; /// <summary> /// whether it has been processed /// </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 ;}}}

Author: Xiaozhu zz this article address http://blog.csdn.net/zhujunxxxxx/article/details/44258719 reprint please indicate the source



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.