Use web service discovery to communicate between Java servers and Android clients
I am building a java server application (running on a PC), which uses jmdns to register itself to the local network, and an Android client application that should use network service discovery to discover Java servers, The application successfully discovered the registered java server. However, when I first ran the server and then ran the Android application, the ondiscoverystarted method was called, but the onservicefound method was never triggered - the Android application did not discover the server. In my opinion, this is an unexpected behavior
Success story: Android application log: 08-24 22:42:06.157 NSD_ DISCOVER onCreate 08-24 22:42:06.373 NSD_ Discover: ondiscoverystarted service discovery started 08-24 22:42:30.256 NSD_ Discover: onservicefound known service types:_ http._ tcp. 08-24 22:42:30.293 NSD_ DISCOVER:onServiceResolved Resolve Succeeded. name:NsdApp,type:._ http._ tcp,host:/10.0.0.2,port:52288
Java server log: start registration end waiting_ FOR_ Message Hello, world end_ THREAD
Failure cases:
Android App log: 08-24 22:05:21.690 NSD_ DISCOVER:onCreate 08-24 22:05:21.908 NSD_ Discover: ondiscoverystarted service discovery started
Java server log: start registration end waiting_ FOR_ MESSAGE
Server code
public class Server {
public static String mServiceName = "NsdApp";
public static final String SERVICE_TYPE = "_http._tcp.local";
static ServerSocket mServerSocket;
public static void main(String[] args) throws IOException {
System.out.println("START");
try {
mServerSocket = new ServerSocket(0);
} catch (IOException e) {
System.out.println("ServerSocket(0) Failed");
}
int mPort = mServerSocket.getLocalPort();
JmDNS jmdns = JmDNS.create();
ServiceInfo info = ServiceInfo.create(SERVICE_TYPE, mServiceName, mPort, "B");
jmdns.registerService(info);
System.out.println("REGISTERED");
jmdns.close();
Thread mReceiveMessage = new Thread(new ReceiveMessage());
mReceiveMessage.start();
System.out.println("END");
}
public static class ReceiveMessage implements Runnable {
public void run() {
System.out.println("WAITING_FOR_MESSAGE");
try {
Socket clientSocket = mServerSocket.accept();
InputStreamReader inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String message = bufferedReader.readLine();
System.out.println(message);
bufferedReader.close();
inputStreamReader.close();
clientSocket.close();
System.out.println("END_THREAD");
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
Customer code
public class MainActivity extends Activity {
public static final String TAG = "NSD_DISCOVER";
public static final String SERVICE_TYPE = "_http._tcp.";
NsdManager.DiscoveryListener mDiscoveryListener;
NsdManager.ResolveListener mResolveListener;
NsdManager mNsdManager;
int port;
InetAddress host;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "onCreate");
mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
initializeResolveListener();
initializeDiscoveryListener();
mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
@Override
public void onDiscoveryStarted(String regType) {
Log.v(TAG, "onDiscoveryStarted Service discovery started");
}
@Override
public void onServiceFound(NsdServiceInfo service) {
if (!service.getServiceType().equals(SERVICE_TYPE)) {
Log.v(TAG, "onServiceFound UnkNown Service Type: " + service.getServiceType());
} else {
Log.v(TAG, "onServiceFound KNown Service Type: " + service.getServiceType());
mNsdManager.resolveService(service, mResolveListener);
}
}
@Override
public void onServiceLost(NsdServiceInfo service) {
Log.e(TAG, "service lost" + service);
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
}
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery Failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery Failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
};
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "onResolveFailed Resolve Failed" + errorCode);
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.v(TAG, "onServiceResolved Resolve Succeeded. " + serviceInfo);
port = serviceInfo.getPort();
host = serviceInfo.getHost();
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
};
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Socket client;
PrintWriter printwriter;
client = new Socket(host, port);
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write("hello world");
printwriter.flush();
printwriter.close();
client.close();
} catch (UnkNownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
resolvent:
You call jmdns.close () immediately after you register. As long as you open jmdns, your service can be found. You should delete the call to close it, make your jmdns variable a member of your class, and then call close. only when you don't want your service to be found. In addition, calling unregisterAllServices () before closing jmdns is a good form.