我在UWP项目中使用Windows.Networking.ServiceDiscovery.Dnssd API来注册DnssdServiceInstance以使用以下代码在网络上广播:
//Service Broadcast
_listener = new StreamSocketListener();
_listener.ConnectionReceived += _listener_ConnectionReceived;
await _listener.BindServiceNameAsync("56788");
string userid = SettingsHelper.GetSetting("userid").ToString();
_service = new DnssdServiceInstance(userid + "._listen._tcp.local",
NetworkInformation.GetHostNames().FirstOrDefault(x => x.Type == HostNameType.DomainName && x.RawName.Contains("local")),
UInt16.Parse(_listener.Information.LocalPort));
await _service.RegisterStreamSocketListenerAsync(_listener);
该服务创建得很好但永远不会从网络中删除。我一直在使用DeviceWatcher查看所有创建的实例。即使在处理StreamSocketListener并将其设置为null时也是如此。
更新:当重新启动创建服务的计算机时,所有创建的服务都消失了......但是当创建服务的应用程序关闭时却没有
API中没有提及服务删除。这是一个错误还是我错过了什么?
由于
答案 0 :(得分:1)
解决方案是同时处理streamsocket并将StreamSocketListener和服务实例设置为null。
来自微软测验游戏示例:
/// <summary>
/// Unregisters and removes the DNS-SD service. If this method is not called,
/// the registration will remain discoverable, even if the app is not running.
/// </summary>
public override bool StopAdvertising()
{
if (_socket != null && _service != null)
{
_socket.ConnectionReceived -= MessageToConnectReceivedFromParticipantAsync;
_socket.Dispose();
_socket = null;
_service = null;
return true;
}
return false;
}