问题描述
我正在使用 .NET 2.0 并创建了一个相当简单的 udp 广播应用程序和 UDP 侦听器.
I'm using .NET 2.0 and have created a fairly simple udp broadcast app and UDP listener.
监听代码:
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 个单选按钮、按钮和一个文本框.
The server is just a simple windows app with 3 radio buttons, button and a textbox.
当我在单独的计算机上运行服务器并选择 radioButton3 时,我在客户端侦听器(在 ip 地址 172.16.75.15 上运行)上接收到消息就好了.但是,如果我选择第一个或第二个单选按钮(创建广播或 255.255.255.255 作为 IP 地址),我什么也得不到.现在,如果我在与服务器相同的电脑上运行客户端,我可以使用这两个选项接收消息.
When I run the server on a separate computer and choose radioButton3 I receive the message just fine on my client listener (which is running on ip address 172.16.75.15). However if I choose the first or second radiobutton (which creates Broadcast or 255.255.255.255 as the ip address) I get nothing. Now if I run the client on the same pc as the server I can receive the message using those two choices.
我不确定我做错了什么,或者是否有某种防火墙阻止了 LAN 上的 UDP 消息.有什么想法吗?
I'm not sure what I'm doing wrong or if there could be some kind of firewall preventing UDP messages on the LAN. Any ideas?
谢谢,
克雷格
推荐答案
仅尝试在本地子网上进行广播.IE 如果您的子网是 255.255.255.0,请尝试广播 172.16.75.255.可能是 Windows、路由器甚至网卡自动阻止通用广播作为预防措施.
Try a broadcast on the local subnet only. IE if your subnet is 255.255.255.0 try a broadcast of 172.16.75.255. It may be that windows, a router or even network card automatically block universal broadcasts as a preventative measure.
这篇关于C# UDP 广播客户端/服务器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!