以下简单安排有什么不对。我所做的就是创建一个多播消息的UDP广告商,以及一个加入多播组以接收此消息的侦听器,两者都在同一台机器上运行。
string Port = "54153";
HostName Host = new HostName("224.3.0.5"); //a multicast range address
//listener
var L = new DatagramSocket();
L.MessageReceived += (sender2, args) => { /*something*/ };
await L.BindServiceNameAsync(Port);
L.JoinMulticastGroup(Host);
//advertiser
var AdvertiserSocket = new DatagramSocket();
AdvertiserSocket.Control.MulticastOnly = true;
Stream outStream = (await AdvertiserSocket.GetOutputStreamAsync(Host, Port)).AsStreamForWrite();
using (var writer = new StreamWriter(outStream))
{
await writer.WriteLineAsync("MESSAGE");
await writer.FlushAsync();
}
听众根本没有收到任何内容(MessageReceived
从未调用过)。我尝试了以下变化但没有成功:
MulticastOnly
255.255.255.255
作为主持人。答案 0 :(得分:3)
广告客户似乎正确地组播数据(TCPView显示已发送的数据包),但接收端口没有得到任何数据。
感谢您分享此问题。我做了一个演示并做了一些测试。我发现侦听器套接字在组中发送了一条消息之前不会收到任何消息。
因此,目前的解决方法是在注册后立即发送空消息:
private async void btnListen_Click(object sender, RoutedEventArgs e)
{
socket = new DatagramSocket();
socket.MessageReceived += Socket_MessageReceived;
socket.Control.MulticastOnly = true;
await socket.BindServiceNameAsync(serverPort);
socket.JoinMulticastGroup(serverHost);
SendWithExistingSocket(socket, "");//send an empty message immediately
}
private async void SendWithExistingSocket(DatagramSocket socket, String text)
{
if (socket != null)
{
Stream stream = (await socket.GetOutputStreamAsync(serverHost, serverPort)).AsStreamForWrite();
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(text);
await writer.FlushAsync();
}
}
}
至于这个问题的根本原因,我会咨询相关团队,并在收到回复后通知你。