rt, C#实现Zero Config(Zeroconf, 无线网络零配置)监听服务代码
Zeroconf的知识可以参考:
references:
nunit.framework.dll NUnit的dll。
Zeroconf.dll Zeroconf的dll。
Codes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zeroconf;
using NUnit.Framework;
namespace ZeroconfServiceBrowserTest
{
[TestFixture]
public class ZeroconfServiceBrowserTest
{
private const string serviceType = "_earth_desktop_services._tcp.local.";
private ZeroconfService zeroService = new ZeroconfService(false);
private ZeroconfServiceListener listener = new ZeroconfServiceListener();
[SetUp]
public void SetUp()
{
zeroService.Start();
zeroService.RegisterServiceListener(serviceType, listener);
}
[TearDown]
public void TearDown()
{
zeroService.Stop();
}
[Test]
public void Test()
{
List<string> serverNameList = null;
string serverName = Environment.MachineName.ToLower() + "." + serviceType;
int i = 3;
while (i > 0)
{
serverNameList = zeroService.ListServiceName(serviceType);
if (serverNameList.Count > 0)
{
break;
}
i--;
System.Threading.Thread.Sleep(2000);
}
Assert.IsTrue(serverNameList.Count > 0, "Failed to browse any services");
}
}
/// <summary>
/// Delegate for service added and removed
/// </summary>
/// <param name="serviceInfo"></param>
public delegate void HandleService(ServiceInfo serviceInfo);
/// <summary>
/// Represents a zeroconf service listener
/// </summary>
public class ZeroconfServiceListener : IZeroconfServiceListener
{
public HandleService listenerDeleAdd { get; set; }
public HandleService listenerDeleRemove { get; set; }
/// <summary>
/// Handle service added
/// </summary>
/// <param name="serviceInfo"></param>
public void HandleServiceAdded(ServiceInfo serviceInfo)
{
if (listenerDeleAdd != null)
{
listenerDeleAdd(serviceInfo);
}
}
/// <summary>
/// Handle service removed
/// </summary>
/// <param name="serviceInfo"></param>
public void HandleServiceRemoved(ServiceInfo serviceInfo)
{
if (listenerDeleRemove != null)
{
listenerDeleRemove(serviceInfo);
}
}
}
}