阅读背景:

两个进程,或者多个进程同时监听一个端口,邦定同一个端口,

来源:互联网 
 void ReceiveTest()
        {
            //1 创建套节字      
            System.Net.Sockets.Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            s.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReuseAddress,true);
           // s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //2 绑定到 4567 端口           
            IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 4503);
            EndPoint ep = (EndPoint)ipe;
            ////////////////重用端口 ,邦定同一个端口,///////////////
            //这一句是一定要加的,加上这句可以使得两个程序监听同一个端口
            s.ExclusiveAddressUse = false;
            //重用端口
            s.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //////////////////
            s.Bind(ep);
            //3 加入多播组 234.5.6.7           
            MulticastOption optionValue = new MulticastOption(IPAddress.Parse("239.239.239.239"));
            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, optionValue);
            //4 接收多播组数据            
            Console.WriteLine("开始接收多播组 234.5.6.7 上的数据...");
            byte[] buffer = new byte[1024];
            while (true)
            {
                int nRet = s.ReceiveFrom(buffer, ref ep);
                if (nRet > 0)
                {
                    string data = Encoding.UTF8.GetString(buffer, 0, nRet);
                    Console.WriteLine(data);
                    uClient.Send(System.Text.Encoding.GetEncoding("GB2312").GetBytes("这是IIS发过来的"), 15);
                }
            }
        } void ReceiveTest()
        {
            //1 创



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: