• .NET 简单实现广播


    代码
        class Program
        {

            
    static bool connecting = true;
            
    static void Main()
            {
                Received();
                
    while (connecting)
                {
                    
    string content = Console.ReadLine();
                    
    if (content.Length > 0)
                    {
                        
    if (string.Compare(content, "<Stop>"true== 0)
                        {
                            Console.WriteLine(
    "关闭...");
                            connecting 
    = false;
                        }
                        
    else
                        {
                            Send(content);
                        }
                    }
                }
                Console.ReadKey();
            }

            
    public static void Send(string content)
            {
                Socket sock 
    = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                
    //IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);//255.255.255.255 
                IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.100.255"), 9050);
               
    // string hostname = Dns.GetHostName();
                byte[] data = Encoding.ASCII.GetBytes(content);
                sock.SetSocketOption(SocketOptionLevel.Socket,
                SocketOptionName.Broadcast, 
    1);
                
    //sock.SendTo(data, iep1);
                sock.SendTo(data, iep2);
                sock.Close();
            }

            
    public static void Received()
            {
                ThreadPool.QueueUserWorkItem((x) 
    =>
                {
                    Socket sock 
    = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    IPEndPoint iep 
    = new IPEndPoint(IPAddress.Any, 9050);
                    sock.Bind(iep);
                    EndPoint ep 
    = (EndPoint)iep;

                    
    byte[] data;
                    
    int recv;
                    
    string stringData;
                    Console.WriteLine(
    "接听开启...");
                    
    while (connecting)
                    {
                        data 
    = new byte[1024];
                        recv 
    = sock.ReceiveFrom(data, ref ep);
                        stringData 
    = Encoding.ASCII.GetString(data, 0, recv);
                        Console.WriteLine(
    "信息: {0} 来自: {1}", stringData, ep.ToString());
                    }
                    Console.WriteLine(
    "接听关闭...");
                    sock.Close();
                });
            }

        }
  • 相关阅读:
    ssh图示+hibernate图示
    spring Transactional
    Spring datasource
    sqlloader导入数据
    Spring Aop Annotation(@Pointcut)
    ajax传输文件+检验
    Spring Aop Annotation
    JDK的动态代理
    nginx代理gitlab
    python相关
  • 原文地址:https://www.cnblogs.com/sofire/p/1738627.html
Copyright © 2020-2023  润新知