以下简单安排有什么问题。我要做的就是创建一个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
作为主机。 最佳答案
感谢您分享这个问题。我做了一个演示并做了一些测试。我发现监听器套接字在该组中发送了一条消息之前将不会收到任何消息。
因此,当前的解决方法是在注册监听后立即发送空消息:
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();
}
}
}
至于此问题的根本原因,我将与相关团队协商,并在得到回复后告知您。
关于c# - 通过 socket 进行最简单的广告/收听安排,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39722217/