我正在尝试使用UDP多播设置自动发现,并使用来自互联网的一些示例代码.这似乎当我运行在客户端和在同一台机器上的服务器工作正常,但是当我在不同的机器上运行它们,无论是与一机在虚拟机上运行我的机器(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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
和客户:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
如此看来,这是公布了其在VirtualBox的UDP数据包仅主机网络接口,由于某种原因,而不是所有的机器都连接到无线网络.只需要弄清楚如何让它不这样做......所以在答案中添加了分辨率......
所以问题结果是因为我有一个以上的活动网络连接,它选择一个并使用它,这导致UDP数据包在客户端正在侦听的不同网络连接上发送出去.因为我已经安装了虚拟机盒,它已经安装并激活了VirtualBox仅主机网络适配器,因此可以支持仅主机网络连接.当我将VirtualBox切换到仅主机模式时,数据包开始被接收.禁用VirtualBox适配器并切换回桥接连接也很有效.