Common.UdpLib

來源:互聯網
上載者:User

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;

namespace Common.UdpLib
{
    public class _Bgz_UdpState
    {
        public IPEndPoint _UdpClientAddress = new IPEndPoint(IPAddress.Any, 0);
        public byte[] _Buffer = new byte[0];

        public _Bgz_UdpState()
        {
            _UdpClientAddress = new IPEndPoint(IPAddress.Any, 0);
            _Buffer = new byte[0];
        }

        public string StrUpdClientAddress
        {
            get
            {
                return _UdpClientAddress.Address.ToString() + ":" + _UdpClientAddress.Port.ToString();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;

namespace Common.UdpLib
{

    public enum ErrorType { MaxConnect, Catch, DisConnect, DisAccept };

    //Udp
    public delegate void _Bgz_OnUdpBindEventDelegate(_Bgz_UdpState state);
    public delegate void _Bgz_OnUdpErrorEventDelegate(ErrorType errortype, string errormsg, _Bgz_UdpState state);
    public delegate void _Bgz_OnUdpReceiveEventDelegate(_Bgz_UdpState state);
}

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;

namespace Common.UdpLib
{
    public class UdpSocket
    {
        private UdpClient _listener = new UdpClient();
        private int _port= 0;
        private bool _debug;
        private Thread _thread;

        private struct ClientInfo
        {
            public string IpAddress;
            public int Port;
            public ClientInfo(string IpAddress, int Port)
            {
                this.IpAddress = IpAddress;
                this.Port = Port;
            }

            public ClientInfo(IPEndPoint ip)
            {
                this.IpAddress = ip.Address.ToString();
                this.Port = ip.Port;
            }

            public string ClientID
            {
                get
                {
                    return IpAddress + ":" + Port.ToString();
                }
            }

            public IPEndPoint GetIPEndPoint(string IpAddress, int Port)
            {
                try
                {
                    IPAddress ip = Dns.GetHostEntry(IpAddress).AddressList[0];
                    return new IPEndPoint(ip, Port);
                }
                catch
                {
                    return new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);
                }
            }

            public IPEndPoint IPEndPoint
            {
                get
                {
                    return GetIPEndPoint(this.IpAddress, this.Port);
                }
            }

        }

        private List<ClientInfo> _clientInfo;
        #region define delegates
        /// <summary>
        /// 伺服器綁定後處理事件 
        /// </summary>
        public _Bgz_OnUdpBindEventDelegate FOnBindEventDelegate;

        /// <summary>
        /// 接收到用戶端資料後處理事件
        /// </summary>
        public _Bgz_OnUdpReceiveEventDelegate FOnReceiveEventDelegate;
        /// <summary>
        /// 報錯資訊處理
        /// </summary>
        public _Bgz_OnUdpErrorEventDelegate FOnErrorEventDelegate;
        #endregion

        #region Event
        private void OnBindEvent(_Bgz_UdpState state)
        {
            if (FOnBindEventDelegate != null) FOnBindEventDelegate(state);
        }
        private void OnReceiveEvent(_Bgz_UdpState state)
        {
            if (FOnReceiveEventDelegate != null) FOnReceiveEventDelegate(state);
        }
        private void OnErrorEvent(ErrorType errortype, string msg, _Bgz_UdpState state)
        {
            if (FOnErrorEventDelegate != null) FOnErrorEventDelegate(errortype, msg, state);
        }
        #endregion

        #region Constructor and Destructor
        public UdpSocket()
        {
        }

        public UdpSocket(int port)
        {
            _port = port;
        }

        ~UdpSocket()
        {
            Stop();
        }
        #endregion

        #region Private Methods

        private void Receive()
        {
            try
            {
                _Bgz_UdpState stx = new _Bgz_UdpState();
                while (true)
                {
                    stx._Buffer = new byte[0];
                    stx._UdpClientAddress = new IPEndPoint(IPAddress.Any, _port);

                    stx._Buffer = _listener.Receive(ref stx._UdpClientAddress);

                    ClientInfo ci = new ClientInfo(stx._UdpClientAddress.Address.ToString(), _port);
                    if (!_clientInfo.Contains(ci))
                    {
                        _clientInfo.Add(ci);
                    }

                    OnReceiveEvent(stx);
                }
            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "ReceiveCallback.2 Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
            }
        }

        #endregion

        #region Public Methods

        public void Start()
        {
            try
            {
                _listener = new UdpClient(_port);
                _Bgz_UdpState stx = new _Bgz_UdpState();
                stx._Buffer = new byte[0];
                stx._UdpClientAddress = new IPEndPoint(IPAddress.Any, _port);

                OnBindEvent(stx);
                _clientInfo = new List<ClientInfo>(100);
            
                _thread = new Thread(new ThreadStart(Receive));
                _thread.Name = "UdpServer Listener";
                _thread.Start();
            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "Start Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
            }
        }

        public void Stop()
        {
            try
            {
                _clientInfo.Clear();

                this._listener.Close();

                if (this._thread.IsAlive)
                {
                    this._thread.Abort();
                }
            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "Send Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
            }
        }

        public void Send(string hostname, int port, byte[] msg)
        {
            try
            {
                IPAddress ip = Dns.GetHostEntry(hostname).AddressList[0];
                _listener.Send(msg, msg.Length, new IPEndPoint(ip, port));
            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "Send Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
            }
        }

        public void Send(IPEndPoint ip, byte[] msg)
        {
            try
            {
                _listener.Send(msg, msg.Length, ip);
            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "Send Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
            }
        }

        public void Send(byte[] msg)
        {
            foreach(ClientInfo c in _clientInfo)
            {
                Send(c.IPEndPoint, msg);
            }
        }

        #endregion

        #region property

        public bool Debug
        {
            get
            {
                return _debug;
            }
            set
            {
                _debug = value;
            }
        }
 
        #endregion
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.