通过套接字的最简单 advertise/listen 排列

Simplest possible advertise/listen arrangement through sockets

下面简单的排列有什么问题。我所做的就是创建一个多播消息的 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 从未调用过)。我尝试了以下变体但没有成功:

  1. 调用和不调用广告商的 BindServiceNameAsync()。
  2. 对广告商、听众或两者使用MulticastOnly
  3. 先创建一个对象再等待几秒钟。
  4. 使用 255.255.255.255 作为主机。

It seems like the advertiser is multicasting data correctly (TCPView shows sent packets), but the receiving port is not getting anything.

感谢您分享这个问题。我做了一个演示并做了一些测试。我发现侦听器套接字在组中发送一条消息之前不会收到任何消息。

因此,目前的解决方法是在注册收听后立即发送一条空消息:

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();
        }
    }
}

关于这个问题的根本原因,我会咨询相关团队,得到回复后会告诉你。