Newer
Older
IrisServerWebSocket / src / main / java / com / ntlab / irisserver / websockets / HelloWorldWebSocket.java
Kota on 11 Dec 2022 1 KB websocketの修正
package com.ntlab.irisserver.websockets;

import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


// 5秒に1回HelloWorldを送るデモ
@ServerEndpoint("/hello-websocket")
public class HelloWorldWebSocket extends TextWebSocketHandler {
    private static final Queue<Session> sessions = new ConcurrentLinkedQueue<>();

    static {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleWithFixedDelay(HelloWorldWebSocket::broadcast, 5, 5, TimeUnit.SECONDS);
    }

    @OnMessage
    public String onMessage(String message) {
        System.out.println("WebSocketで受信したメッセージ/ " + message);
        return "WebSocketでメッセージを正常に受信しました!";
    }

    @OnError
    public void onError(Throwable th) {
        System.out.println("WebSocketエラーが発生/ " + th.getMessage());
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocketセッション確立");
        sessions.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocketセッション終了");
        sessions.remove(session);
    }

    public static void broadcast() {
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        sessions.forEach(session -> {
            session.getAsyncRemote().sendText("HelloWorld! : " + formatter.format(now));
        });
    }

}