Skip to content

Commit

Permalink
allow ping text messages
Browse files Browse the repository at this point in the history
this is required as browsers don't allow to directly send ping and receive pong messages. Therefore, the client is forced to send pings as text messages and pongs must be received as text messages. Otherwise, the client has no information if the connection is actually stale or still alive.
  • Loading branch information
derklaro committed Jan 6, 2025
1 parent 51c9388 commit 70bbf46
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PingMessage;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
Expand All @@ -54,8 +55,8 @@ public EventWebsocketHandler(@Nonnull EventSessionManager sessionManager) {
@Override
@SuppressWarnings("unchecked")
public void afterConnectionEstablished(@Nonnull WebSocketSession session) {
// don't allow any data to be sent from the client
session.setTextMessageSizeLimit(0);
// don't allow any data to be sent from the client, except for ping messages
session.setTextMessageSizeLimit(4);
session.setBinaryMessageSizeLimit(0);

// get the frame types added by the handshake interceptor and register the session
Expand All @@ -79,6 +80,8 @@ public void handleMessage(@Nonnull WebSocketSession session, @Nonnull WebSocketM
case PingMessage _ -> eventSession.sendPong();
// received pong from the client, mark the client as alive
case PongMessage _ -> eventSession.handlePongReceive();
// client sends a ping in form of a text message, respond with a pong text message
case TextMessage tm when tm.getPayload().equals("ping") -> eventSession.sendPongText();
// reject all other type of websocket messages being sent by the client
default -> session.close(CloseStatus.NOT_ACCEPTABLE);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ public void sendPong() throws IOException {
this.webSocketSession.sendMessage(new PongMessage());
}

/**
* Sends out a text message with the data "pong".
*/
public void sendPongText() throws IOException {
this.sendText("pong");
}

/**
* Sends the given text as a text frame to the websocket connection.
*
Expand Down

0 comments on commit 70bbf46

Please sign in to comment.