android nsd服务
2016-06-16 本文已影响1514人
冰风47
全称为: Network Service Discovery.
作用为: The addition of Network Service Discovery (NSD) takes this further by allowing an application to seek out a nearby device running services with which it can communicate. (也就是说使用这个服务就可以搜索附近哪个设备可以进行通信).
关于NSD的开发笔记.
- 注册自己的服务, 目的是设定协议以及端口. 只有设定好了自己的服务属性, 才能进行下一步的网络服务匹配.
- 发现网络内的各个服务.
需要注意的是在发现监听器(DiscoveryListener)里, 当某个service找到的时候, 需要做一些条件判断:类型匹配, 服务名字匹配这样的操作. 当服务名字完全一致的时候, 说明自己被找到了, 要过滤掉. 也就是说, 查找目标也包括自己. - 发现流程:
(1) 注册nsd服务.
(2) 初始化注册监听器
(3) 初始化发现监听器
(4) 初始化处理监听器
(5) 注销nsd服务 - 具体实现代码如下(借鉴自官方教程):
(1)
public void registerService(int port) {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName(NSD_SERVICE_NAME);
serviceInfo.setPort(port);
serviceInfo.setServiceType(NSD_SERVER_TYPE);
mNsdManager = (NsdManager) mCurrentContext.getSystemService(Context.NSD_SERVICE);
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
(2)
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
}
@Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
mServerName = serviceInfo.getServiceName();
}
@Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
}
};
}
(3)
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
mNsdManager.stopServiceDiscovery(this);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
mNsdManager.stopServiceDiscovery(this);
}
@Override
public void onDiscoveryStarted(String serviceType) {
}
@Override
public void onDiscoveryStopped(String serviceType) {
}
@Override
public void onServiceFound(NsdServiceInfo serviceInfo) {
if (!serviceInfo.getServiceType().equals(NSD_SERVER_TYPE)) {
} else if (serviceInfo.getServiceName().equals(NSD_SERVICE_NAME)) {
} else if (serviceInfo.getServiceName().contains(NSD_SERVICE_NAME)) {
mNsdManager.resolveService(serviceInfo, mResolverListener);
}
}
@Override
public void onServiceLost(NsdServiceInfo serviceInfo) {
}
};
}
(4)
public void initializeResolveListener() {
mResolverListener = new NsdManager.ResolveListener() {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
if (serviceInfo.getServiceName().equals(mServerName)) {
Log.d(logTitle, "Same IP.");
return;
}
mService = serviceInfo;
int port = mService.getPort();
InetAddress host = mService.getHost();
}
};
}
(5)
public void unInitService() {
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}