我在 Windows 8 Metro 程序中实现 SSDP 发现时遇到问题。下面是代码:
public async Task SearchForDevices()
{
var socket = new DatagramSocket();
socket.MessageReceived += async (sender, args) =>
{
Debug.WriteLine("Received data" + DateTime.Now);
DataReader reader = args.GetDataReader();
uint count = reader.UnconsumedBufferLength;
string data = reader.ReadString(count);
Debug.WriteLine(data);
var response = new Dictionary<string, string>();
foreach (
string x in
data.Split(new[] {"\r\n", "\n"}, StringSplitOptions.None))
{
if (x.Contains(":"))
{
string[] strings = x.Split(':');
response.Add(strings[0].ToLower(), x.Remove(0, strings[0].Length + 1));
}
}
Device device = await GetXml(response);
Debug.WriteLine("Device found");
if (DeviceFound != null)
DeviceFound(this, new DeviceFoundEventArgs(device));
};
await socket.BindEndpointAsync(null, "");
HostName hostName = new HostName("239.255.255.250");
socket.JoinMulticastGroup(hostName);
string message = "M-SEARCH * HTTP/1.1\r\n" +
"HOST: " + hostName.DisplayName + ":1900\r\n" +
"ST: upnp:rootdevice\r\n" +
"MAN: \"ssdp:discover\"\r\n" +
"MX: 3\r\n\r\n";
DateTime start = DateTime.Now;
TimeSpan interval = new TimeSpan(0, 0, 30);
Debug.WriteLine(start);
IOutputStream stream = await socket.GetOutputStreamAsync(hostName, "1900");
var writer = new DataWriter(stream) { UnicodeEncoding = UnicodeEncoding.Utf8 };
writer.WriteString(message);
await writer.StoreAsync();
await Task.Delay(1500);
}
这段代码根本不可靠。大约 50% 的时间它找不到连接的设备,而其他发现可以找到。但有时它会起作用。
我的网络嗅探器 (SmartSniff) 有时甚至无法捕获其 SSDP 请求,即使我已经多次拨打电话。
我不认为这是一个异步问题,因为它偶尔会起作用。请帮我 !谢谢!