码迷,mamicode.com
首页 > 其他好文 > 详细

简单 UDP 操作类

时间:2017-04-05 11:46:13      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:string   ring   rms   信息   sock   try   内容   ace   names   

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace moniopter
{
    public static class UDPManager
    {
        //本机名称和IP
        public static string ComputerName;
        public static string ComputerIP;

        public const int listenProt = 10318;//设置端口号
        static UdpClient listener = null;//提供的网络服务
        static Thread listenter = null;//创建一个监听消息的进程
        static bool islistenter;//是否要监听
        public static Queue MsgList = new Queue();//存放所有的消息【文字类】
        static UDPManager()
        {
            ComputerName = Dns.GetHostName();
            ComputerIP = GetIPAddress();
            islistenter = true;

            //加下面这句是为了在开启线程中可以访问控件属性
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            listenter = new Thread(StartListener);
            listenter.Start();
        }

        //关闭
        public static void Close()
        {
            if (listener == null)
            {
                return;
            }
            try
            {
                listener.Close();//关闭探听消息服务
                listenter.Abort();//关闭监听消息进程
            }
            catch{  }
        }

        //获取IP
        private static string GetIPAddress()
        {
            string AddressIP = "";
            //第一种办法获取
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString().ToLower() == "internetwork")
                {
                    return _IPAddress.ToString();
                }
            }
            //第二种办法获取
            if (AddressIP == "")
            {
                IPHostEntry myEntry = Dns.GetHostEntry(System.Net.Dns.GetHostName());
                if (myEntry.AddressList.Length > 1)
                {
                    if (myEntry.AddressList[0].ToString().IndexOf(‘.‘) > 0)
                    {
                        AddressIP = myEntry.AddressList[0].ToString();
                    }
                    else
                    {
                        AddressIP = myEntry.AddressList[1].ToString();
                    }
                    AddressIP = myEntry.AddressList[1].ToString();
                }
                else
                {
                    AddressIP = myEntry.AddressList[0].ToString();
                }
            }
            return AddressIP;
        }

        public delegate void Listenter(string UIP, string msg);

        public static event Listenter OnListenter; 

        //开始监听
        private static void StartListener()
        {
            listener = new UdpClient(listenProt); //使用UDP协议
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenProt); //任意IP,
            try
            {
                while (islistenter)//处于监听状态
                {
                    byte[] bytes = listener.Receive(ref groupEP);
                    string Uip = groupEP.Address.ToString();//发信人的IP
                    string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0,
                    bytes.Length);//获得信息
                    string[] msg = { Uip, strInfo };//放入ip,和内容
                    MsgList.Enqueue(msg);
                    OnListenter(Uip, strInfo);
                }
            }
            catch { }
            finally
            {
                listener.Close();
            }
        }

        /// <summary>
        /// 发送消息 string
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="ipStr"></param>
        public static void Send(string msg, string ipStr)
        {
            Socket s = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);
            try
            {
                IPAddress broadcast = IPAddress.Parse(ipStr);
                byte[] sendbuf = Encoding.GetEncoding("gb2312").GetBytes(msg);
                IPEndPoint ep = new IPEndPoint(broadcast, listenProt);

                //65507 可发送最大byte  64512
                if (sendbuf.Length <= 64512)
                {
                    s.SendTo(sendbuf, ep);
                }
            }
            catch { }
            finally
            {
                s.Close();
            }
        }

    }
}

  

简单 UDP 操作类

标签:string   ring   rms   信息   sock   try   内容   ace   names   

原文地址:http://www.cnblogs.com/weloglog888/p/6667921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!