Java を使用して Websocket 接続終了例外を解決する方法。具体的なコード例が必要です。
はじめに:
1. Websocket 接続終了例外の種類
2. Websocket 接続終了例外の処理方法
@ClientEndpoint public class WebSocketClient { private final static Logger logger = Logger.getLogger(WebSocketClient.class.getName()); private Session session; private final Lock reconnectLock = new ReentrantLock(); private final Condition reconnectCondition = reconnectLock.newCondition(); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); private final ExponentialBackoff backoff = new ExponentialBackoff(3, 1000, 30000); @OnOpen public void onOpen(Session session) { this.session = session; logger.info("Websocket connection opened"); } @OnClose public void onClose() { logger.info("Websocket connection closed"); reconnect(); } @OnError public void onError(Throwable e) { logger.log(Level.SEVERE, "Websocket connection error", e); reconnect(); } public void reconnect() { if (reconnectLock.tryLock()) { try { long delay = backoff.nextDelay(); logger.info("Reconnecting in " + delay + " ms"); executorService.schedule(() -> { try { connect(); backoff.reset(); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to reconnect", e); reconnect(); } }, delay, TimeUnit.MILLISECONDS); } finally { reconnectLock.unlock(); } } } public void connect() throws Exception { // Code to connect to websocket server } }
@ServerEndpoint("/websocket") public class WebSocketServer { private static CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>(); @OnOpen public void onOpen(Session session) { sessions.add(session); // Code to handle connection open } @OnClose public void onClose(Session session) { sessions.remove(session); // Code to handle connection close } @OnError public void onError(Session session, Throwable throwable) { // Code to handle connection errors } }
以上がJavaを使用してWebSocket接続終了例外を解決する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。