Newer
Older
IrisServerWebSocket / src / main / java / com / ntlab / irisserver / websockets / HelloWebSocket.java
package com.ntlab.irisserver.websockets;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
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 HelloWebSocket {
    private static final Queue<Session> sessions = new ConcurrentLinkedQueue<>();

    static {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleWithFixedDelay(HelloWebSocket::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));
        });
    }

}