我正在使用.NET 2.0并创建了一个相当简单的udp广播应用程序和UDP侦听器.
听众代码:
Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); IPEndPoint localEndPoint = new IPEndPoint( IPAddress.Any, 11000 ); listener.Bind( localEndPoint ); EndPoint ep = (EndPoint)localEndPoint; Console.WriteLine("Ready to receive…"); byte[] data = new byte[1024]; int recv = listener.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); listener.Close();
服务器代码:
int groupPort = 11000; IPEndPoint groupEP = new IPEndPoint( IPAddress.Parse( "255.255.255.255" ), groupPort ); if ( radioButton2.Checked ) { groupEP = new IPEndPoint( IPAddress.Broadcast, groupPort ); } else if ( radioButton3.Checked ) { groupEP = new IPEndPoint( IPAddress.Parse( "172.16.75.15" ), groupPort ); } Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1 ); socket.SendTo( System.Text.ASCIIEncoding.ASCII.GetBytes( testTextBox.Text ), groupEP );
服务器只是一个简单的Windows应用程序,带有3个单选按钮,按钮和文本框.
当我在一台单独的计算机上运行服务器并选择radioButton3时,我在客户端侦听器(在ip地址172.16.75.15上运行)上收到了正确的消息.但是,如果我选择第一个或第二个radiobutton(创建广播或255.255.255.255作为IP地址),我什么也得不到.现在,如果我在与服务器相同的PC上运行客户端,我可以使用这两个选项接收消息.
我不确定我做错了什么,或者是否有某种防火墙阻止了局域网上的UDP消息.有任何想法吗?
谢谢,
克雷格
仅在本地子网上尝试广播.IE如果您的子网是255.255.255.0尝试播放172.16.75.255.可能是Windows,路由器甚至网卡自动阻止通用广播作为预防措施.