0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

こんにちは、なりかくんと申します。
この記事はなりかくん Advent Calender 2023の24日目の記事です。(執筆は6日遅れの30日とか言えない。)

今回は、JavaでWebSocketを扱う方法を紹介します。Javaの記事ってなかなか出てこないんですよね。特にSSL対応のやつとか。
(調べ方が悪いのかもしれない。)

Java標準機能のHttpClientでWebSocket

Java標準機能のHttpClientでWebSocketを接続できます。調べてもなかなか出てこなかったのでコードを紹介します。

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;

public final class NarikakunWebSocket {
    private WebSocket ws;

    private void webSocketStart() {
        HttpClient client = HttpClient.newHttpClient();
        WebSocket.Builder wsb = client.newWebSocketBuilder();
        WebSocket.Listener listener = new WebSocket.Listener() {
            @Override
            public void onOpen(WebSocket webSocket){
                // 接続時
                ws.sendText("Hello", true);
            }

            @Override
            public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
                // 切断時
                return null;
            }
        };
        CompletableFuture<WebSocket> comp = wsb.buildAsync(URI.create("WS URL"), listener);
        try {
            ws = comp.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

少しでも参考になればいいなと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?