【发布时间】:2010-10-27 19:33:51
【问题描述】:
我正在尝试使用 UDP 多播设置自动发现,并且正在使用来自 Internet 的一些示例代码。当我在同一台机器上运行客户端和服务器时,这似乎可以正常工作,但是当我在不同的机器上运行它们时,无论是在我的机器(virtualBox)上的虚拟机中运行的机器还是在其他“真实”机器上网络然后其他机器似乎永远不会收到正在广播的消息。
经过一番谷歌搜索,罪魁祸首似乎是路由器 (SpeedTouch 780),它可能会丢弃数据包。我如何检查是否是这种情况?我可以检查他们的其他事情以尝试追查问题吗?可能完全是另外一回事吗?
编码:
服务器代码
using System;
using System.Net.Sockets;
using System.Text;
internal class StockPriceMulticaster
{
private static string[] symbols = {"ABCD", "EFGH", "IJKL", "MNOP"};
public static void Main ()
{
using (UdpClient publisher = new UdpClient ("230.0.0.1", 8899))
{
Console.WriteLine ("Publishing stock prices to 230.0.0.1:8899");
Random gen = new Random ();
while (true)
{
int i = gen.Next (0, symbols.Length);
double price = 400*gen.NextDouble () + 100;
string msg = String.Format ("{0} {1:#.00}", symbols, price);
byte[] sdata = Encoding.ASCII.GetBytes (msg);
publisher.Send (sdata, sdata.Length);
System.Threading.Thread.Sleep (5000);
}
}
}
}
和客户:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class StockPriceReceiver{
public static void Main(){
UdpClient subscriber = new UdpClient(8899);
IPAddress addr = IPAddress.Parse("230.0.0.1");
subscriber.JoinMulticastGroup(addr);
IPEndPoint ep = null;
for(int i=0; i<10;i++){
byte[] pdata = subscriber.Receive(ref ep);
string price = Encoding.ASCII.GetString(pdata);
Console.WriteLine(price);
}
subscriber.DropMulticastGroup(addr);
}
}
编辑
所以它似乎出于某种原因在仅 VirtualBox 主机的网络接口上发布 UDP 数据包,而不是所有机器都连接到的无线网络。只需要弄清楚如何让它不这样做...... 所以在答案中添加了解决方案......
【问题讨论】:
-
您的网络上是 IPv4 还是 IPv6?