Abubakr Shoaliev
Abubakr Shoaliev

Reputation: 3

How to handle ping messages in Java Spring WebSocket

Can you please help me on how can I handle ping messages when extending a websocket handler? Currently I am extending the Spring's AbstractWebSocketHandler, but even though I see that there exists handlePongMessage() method, there is no any handlePingMessage() function.

I have tried to handle ping messages in a following way (see handleMessage() implementation):

    public class MyHandler extends AbstractWebSocketHandler {

        // some other methods here...

        @Override
        public void handleMessage(@NonNull WebSocketSession session, @NonNull WebSocketMessage<?> message) {
            try {
                if (message instanceof PingMessage) {
                    log.info("Received Ping from server. Sending Pong."); // I never see this log in the console when running a program
                    session.sendMessage(new PongMessage(((PingMessage) message).getPayload()));
                    return;
                } else if (! (message instanceof TextMessage)) return;

                String s = (String) message.getPayload();
                // doing some processing here...

            } catch (Exception e) {
                log.error("Failed to read json data");
            }
        }
    }

However, after running the program, the Received Ping from server log is never printed out in the console. Therefore I assume that my implementation doesn't work actually. Moreover, after some time my websocket gets disconnected from the server with the following error: Disconnected from websocket with code 1006 and reason "Unexpected Status of SSLEngineResult after an unwrap() operation" And I assume this happens due to not handling the ping messages.

Thank you a lot for your time!

Upvotes: 0

Views: 58

Answers (1)

scrhartley
scrhartley

Reputation: 1537

The implementation that Spring builds upon doesn't expose receiving pings to user code and just automatically responds with a pong when receiving a ping.
It's the same as this question for JSR 356: Receiving pings with Java EE Websocket API

However... looking at this Chrome bug, it seems that browsers don't necessarily send ping requests.
So you could send pings from the server, implement something equivalent in JS or just rely on the client reconnecting when the connection drops.

There's some discussion here: Sending websocket ping/pong frame from browser

Upvotes: 0

Related Questions