C#UDP广播客户端/服务器无法正常工作 [英] C# UDP broadcast client/server does not work

查看:248
本文介绍了C#UDP广播客户端/服务器无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.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();



服务器代码:

Server code:

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地址),我什么也没得到。现在,如果我在同一台PC作为服务器运行客户端,我可以使用这两个选择接收消息。

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.

我不知道我做错了,或者有可能是某种防火墙防止在局域网上的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?

谢谢,

克雷格

推荐答案

尝试只在本地子网广播。也就是说,如果您的子网为255.255.255.0尝试172.16.75.255的广播。这可能是窗户,路由器,甚至网卡自动拦截普遍的广播作为一种预防措施。

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广播客户端/服务器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆