我在Android主机设备上运行NanoHTTPD网络服务器,该设备正在播放没有互联网连接的Wifi热点。我的主机应用程序通过NsdManager宣传TCP服务,连接到Wifi热点的客户端应用程序将查找。
到目前为止,登录主机设备表明服务器正在启动并且NSD服务已正确注册。但是,我的手机应用程序没有向处理该服务的Web服务器发送任何请求(该应用程序找不到可用的服务)。记录显示我的主机服务器的套接字没有IP地址。但是,当我的手机连接到Wifi热点时,它会获得一个IP地址。为了让主机自己在热点网络上获取IP地址,我有什么特别的东西吗?
以下是我的NanoHTTPD服务器启动功能:
@Override
public void start(final int timeout, boolean daemon) throws IOException {
super.start(timeout, daemon);
ServerSocket socket = getMyServerSocket();
if (!socket.isBound()) {
final InetAddress ip = InetAddress.getLocalHost();
final int port = getListeningPort();
socket.bind(new InetSocketAddress(ip, port));
if (DEBUG) {
Log.d(TAG, "Socket bound manually.");
}
}
if (DEBUG) {
final InetAddress ip = socket.getInetAddress();
final int port = socket.getLocalPort();
Log.d(TAG, String.format("Bound socket to %s:%d", ip.getHostAddress(), port));
}
initRegistrationListener();
registerService();
}
private void initRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
public void onServiceRegistered(NsdServiceInfo aInfo) {
mServiceName = aInfo.getServiceName();
Log.d(TAG, "Nsd service registered: " + mServiceName);
}
@Override
public void onRegistrationFailed(NsdServiceInfo aInfo, int aErrorCode) {
Log.e(TAG, "Nsd service registration failed.");
}
@Override
public void onServiceUnregistered(NsdServiceInfo aInfo) {
Log.d(TAG, "Nsd service unregistered.");
}
@Override
public void onUnregistrationFailed(NsdServiceInfo aInfo, int aErrorCode) {
Log.e(TAG, "Nsd service unregister failed.");
}
};
}
private void registerService() {
final int port = getMyServerSocket().getLocalPort();
final InetAddress addr = getMyServerSocket().getInetAddress();
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName("MyTcpService");
serviceInfo.setServiceType("_my-service._tcp");
serviceInfo.setPort(port);
serviceInfo.setHost(addr);
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
if (DEBUG) {
Log.d(TAG, String.format("Registered service at %s:%d.", addr.getHostAddress(), port));
}
}
运行这些函数的Logcat输出:
11-06 10:56:31.814 2869 2869 D JsonServer: Socket is bound to :::48376
11-06 10:56:31.816 2869 2869 D JsonServer: Registered service at :::48376.
11-06 10:56:34.199 2869 3733 D JsonServer: Nsd service registered: MyTcpService
11-06 10:57:14.160 2869 3733 D JsonServer: Nsd service unregistered.
我绑定的ServerSocket没有IP地址的任何想法?