C# 实现udp广播收集局域网设备代码

写过一篇没放代码,现在放上来

C# 实现udp广播收集局域网设备代码_第1张图片
udpBroadCast

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

namespace UdpBroadCast
{
     
    class Program
    {
     
       
     
         private static Socket sock;
        private static Socket sock2;
        private static IPEndPoint iep1;
         private static byte[] data;
        
         static void Main(string[] args)
         {
     
            //创建UDPsocket通讯实例
             sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);
            //创建一个广播实例,指定端口号9050
             iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
            //获取主机名
             string hostname = GetLocalIP();
             //准备发送字节数组
             data = Encoding.ASCII.GetBytes("if you see this message ,you need to send your info to this ip: "+hostname+"and this port:9060");
            //设置套接字选项
             sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);

            
            //开启线程每两秒广播一次主机IP
            Thread t = new Thread(BroadcastMessage);
             t.Start();
            //sock.Close();
            //开启线程每两秒接收一次消息
            //Thread t2 = new Thread(RecMsg);
            //t2.Start();
            Console.ReadKey();

         }
 
        private static void BroadcastMessage()
         {
     
             while (true)
             {
     
                 Console.WriteLine("广播内容:"+  System.Text.Encoding.Default.GetString(data) );
                 sock.SendTo(data, iep1);
                
                 Thread.Sleep(2000);
             }

         }

        private static void RecMsg() {
     
            sock2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //创建一个端口为9050的终结点
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            //绑定
            sock2.Bind(iep);
            
            EndPoint ep = (EndPoint)iep;
            while (true) {
     
               
                Console.WriteLine("Ready to receive…");
                byte[] data = new byte[1024];
                int recv = sock2.ReceiveFrom(data, ref ep);
                string stringData = Encoding.ASCII.GetString(data, 0, recv);

                Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
                


            }
            //sock2.Close();

        }
        //获取本机IPV4
        public static string GetLocalIP()
        {
     
            try
            {
     
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
     
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
     
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
     
                Console.WriteLine("获取本机IP出错:" + ex.Message);
                return "";
            }
        }






    }
}

udpClient

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

namespace UdpClient
{
     
    class Program
    {
     
        static void Main(string[] args)
        {
     
            //创建一个UDPSocket
            Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
            //创建一个端口为9060的终结点
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9060);
           
            sock.Bind(iep);
            EndPoint ep = (EndPoint)iep;
            Boolean flag = true;
            byte[] data = new byte[1024];
            while (flag) {
     
                
                Console.WriteLine("Ready to receive…");

                
                int recv = sock.ReceiveFrom(data, ref ep);
                string stringData = Encoding.ASCII.GetString(data, 0, recv);
                if (CheckRecStr(stringData)) {
     
                    Console.WriteLine("接收字符串格式正确");
                    //存起来
                }

                Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
                //sock.Close();

            }
            sock.Close();
        }
        /// 
        /// 校验字符串是否符合规范
        /// 
        /// 
        /// 
        public static Boolean CheckRecStr(string msg) {
     
            //包裹在#---&&中,诸如此类##collector&&
            return !String.IsNullOrEmpty(msg) && msg.StartsWith("##") && msg.EndsWith("&&");
        }

        
    }
}

好了

你可能感兴趣的:(socket,C#,c#,udp,socket,局域网)