CoAP Client サンプルコード (Java)

Constrained Application Protocol

前回の記事でCoAPのサーバサンプルを書きましたので、今回はクライアントのサンプルコードです。

tech.misatowater.com

クライアントからのリクエストと、クライアントからRegistration送信後サーバから定期的に送信されるデータを受信する2パターン作成します。

リクエスト→レスポンスパターン

前回作成したサーバのパス"/Hello"にリクエストし、受信結果(レスポンスコード、オプション、レスポンステキスト)を表示します。

public class CaliforniumClient {
    public static void main(String[] args) {
        CoapClient client = new CoapClient();

        try {
            client.setURI("coap://localhost/Hello");
            client.useNONs();
            System.out.println("Request URI: " + client.getURI());

            CoapResponse response = client.get();
            System.out.println(response.getCode());
            System.out.println(response.getOptions());
            System.out.println(response.getResponseText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

observeパターン

リクエスト→レスポンスパターンと同様に、Registration送信後のデータ受信およびエラー時の動作をコールバックで処理します。

public class ObserveClient {
    public static void main(String[] args) {
        CoapClient client = new CoapClient("coap://localhost:5683/obs");

        Executors.newSingleThreadExecutor().execute(() ->
                client.observe(new CoapHandler() {
                    @Override
                    public void onLoad(CoapResponse response) {
                        System.out.println(response.getCode());
                        System.out.println(response.getOptions());
                        System.out.println(response.getResponseText());
                    }

                    @Override
                    public void onError() {
                        System.out.println("observe failed");
                    }
                })
        );
    }
}