我正在尝试通过网络中的网络服务发现API(NSD)连接两个Android设备。在实施过程中,我遵循了Android官方网页。其中一台设备充当服务器,另一台设备充当客户端。我要求网络提供下一个空闲端口。但是,一旦我通过registerService(nsdsInfo,NsdManager.PROTOCOL_DNS_SD,mRegistrationListener)在网络中注册服务器,则nsdsInfo中的参数为空。因此,在调用此代码行之前,nsdsInfo对象包含正确的端口和正确的主机等。调用此方法之后,侦听器onServiceRegistered()中的Callback方法包含Port = 0和Host = null。
是否有任何猜测为什么在注册过程中会丢失端口和主机名,但是注册仍然成功? 另一方面,即使触发了注册回调“ onServiceRegistrered()”,其他设备也无法发现服务器。
预先感谢大家!
//Const
private static final String SERVICE_TYPE = "_speech._tcp";
private static final String SERVICE_NAME = "speech";
public WiFiServiceRegistry(Context ctx) throws IOException {
this.context = ctx;
initializeSocketAndPort();
initializeNsdService();
initializeRegistrationListener();
if (nsdManager == null)
nsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
System.out.println("nsdsinfo host" + nsdsInfo.getServiceName());
System.out.println("nsdsinfo port" + nsdsInfo.getPort());
nsdManager.registerService(nsdsInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
/**
* Initializes the NsdServiceInfo.
*/
private void initializeNsdService(){
nsdsInfo = new NsdServiceInfo();
nsdsInfo.setServiceName(SERVICE_NAME);
nsdsInfo.setServiceType(SERVICE_TYPE);
nsdsInfo.setPort(mLocalPort);
}
/**
* Initializes the socket and port. Parameter 0 means that the next available port is used (dynamic).
* @throws IOException
*/
private void initializeSocketAndPort() throws IOException {
mServerSocket = new ServerSocket(0);
mLocalPort = mServerSocket.getLocalPort();
}
/**
* Inizializes the registrationListener. Keeps track of the registration status.
*/
private void initializeRegistrationListener(){
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
System.out.println("WiFiServiceRegistry: Registration failed");
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
System.out.println("WiFiServiceRegistry: Unregistration failed");
}
@Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
System.out.println("WiFiServiceRegistry: Registered service");
System.out.println("WiFiServiceRegistry: Port " + serviceInfo.getPort());
System.out.println("WiFiServiceRegistry: Host " + serviceInfo.getHost());
System.out.println("WiFiServiceRegistry: ServiceName " + serviceInfo.getServiceName());
}
@Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
System.out.println("WiFiServiceRegistry: Unregistered service");
}
};
}