I am using the californium library for coap communication and it is being deployed on the Android platform. I have started coap server in one device and the client is on another device, both are in the same network.
Server code : Creating a server with below resource
class HelloWorldResource extends CoapResource {
public HelloWorldResource() {
// set resource identifier
super("hello");
// set display name
getAttributes().setTitle("Hello-World Resource");
}
@Override
public void handleGET(CoapExchange exchange) {
// respond to the request
exchange.respond("Hello Android!");
}
}
Client code :
CoapClient coapClient = new CoapClient("coap://localhost/.well-known/core");
try {
Set<WebLink> webLinks = coapClient.discover();
System.out.println(webLinks.size());
} catch (ConnectorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
no output from the above code. I don't know the IP address and I want to communicate with the server. is this the right way or I am missing something?
A "discover" is a special coap request, to discover the resources of a known host.
To discover the host, a mutlicast request may be used, but must be supported by the server.
"localhost" is the address of the device itself. With that, the device will send the discover-request to itself.
If you dont't know the address, you might either use a "multicast" request first (requires also preparation on the server side, see MulticastServer Example. That example is more complex, than you will need. But demonstrates the principles as well). Or you need to lookup that address (android: settings -> Connections -> WLAN -> Settings-Icon : there you see your IP-address.
Discovers a "known" server, not the local-network. Replace the localhost with "californium.eclipseprojects.io" and you will get:
All the received links are relative to the server you send the discover to.