Skip to content

Commit 5210887

Browse files
committed
[bugfix] session cleanup in Websocket
make sure stale sessions don't accumulate and interrupted sessions are handled more gracefully
1 parent 37d5309 commit 5210887

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

exist-core/src/main/java/org/exist/xquery/functions/websocket/WebSocketEndpoint.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import jakarta.websocket.server.ServerEndpoint;
3636
import java.io.IOException;
3737
import java.io.StringWriter;
38+
import java.nio.channels.ClosedChannelException;
3839
import java.util.Iterator;
3940
import java.util.Map;
4041
import java.util.concurrent.ConcurrentHashMap;
@@ -124,6 +125,16 @@ public void closeSession(final Session session, final CloseReason closeReason) {
124125
sessions.remove(session);
125126
}
126127

128+
@OnError
129+
public void onError(final Session session, final Throwable throwable) {
130+
sessions.remove(session);
131+
if (throwable instanceof ClosedChannelException) {
132+
LOG.debug("WebSocket client disconnected abruptly: session {}", session.getId());
133+
} else {
134+
LOG.warn("WebSocket error on session {}: {}", session.getId(), throwable.getMessage(), throwable);
135+
}
136+
}
137+
127138
@OnMessage
128139
public void recv(final String message, final Session session) {
129140
try (final JsonParser parser = JSON_FACTORY.createParser(message)) {
@@ -192,7 +203,8 @@ public static void sendAll(final String toChannel, final String message) {
192203
session.getBasicRemote().sendText(message);
193204
}
194205
} catch (final IOException e) {
195-
LOG.error("Error sending message via websocket: {}", e.getMessage(), e);
206+
LOG.debug("Removing disconnected WebSocket session: {}", e.getMessage());
207+
iterator.remove();
196208
}
197209
}
198210
}

0 commit comments

Comments
 (0)