Skip to content

Handling WebSocket messages

Fluxzero provides first-class support for WebSocket communication, enabling stateful or stateless message handling using the same annotation-based model as other requests.

WebSocket requests are published to the WebRequest log after being reverse-forwarded from the Fluxzero Runtime, and can be consumed and responded to like any other request type.


Use annotations like @HandleSocketOpen, @HandleSocketMessage, and @HandleSocketClose directly on singleton handler classes:

@HandleSocketOpen("/chat")
public String onOpen() {
return "Welcome!";
}
@HandleSocketMessage("/chat")
public String onMessage(String incoming) {
return "Echo: " + incoming;
}
@HandleSocketClose("/chat")
public void onClose(SocketSession session) {
System.out.println("Socket closed: " + session.sessionId());
}

You can return a response directly from onOpen or onMessage. For more control, inject SocketSession and send messages manually.

Other available annotations:

  • @HandleSocketPong — handle pong responses
  • @HandleSocketHandshake — override default handshake logic

Use @SocketEndpoint to create a new handler instance per session, allowing you to store session-local state:

@SocketEndpoint
@Path("/chat")
public class ChatSession {
private final List<String> messages = new ArrayList<>();
@HandleSocketOpen
public String onOpen() {
return "Connected!";
}
@HandleSocketMessage
public void onMessage(String text, SocketSession session) {
messages.add(text);
session.sendMessage("Stored message: " + text);
}
@HandleSocketClose
public void onClose() {
System.out.println("Messages in this session: " + messages.size());
}
}

Stateful sessions are ideal for authentication, accumulating messages, buffering, or managing cursors and sequences.


Fluxzero automatically manages ping/pong logic for connections handled by @SocketEndpoint:

  • Sends pings at regular intervals (default: every 60 seconds)
  • Closes the session if a pong isn’t received in time
  • Customizable using the aliveCheck attribute
@SocketEndpoint(aliveCheck = @SocketEndpoint.AliveCheck(pingDelay = 30, pingTimeout = 15))
public class MySession {
// ...
}

AnnotationDescription
@HandleSocketOpenHandles WebSocket connection opening
@HandleSocketMessageHandles incoming WebSocket messages (text/binary)
@HandleSocketPongHandles pong responses (e.g. from keep-alive)
@HandleSocketCloseHandles WebSocket session closure
@HandleSocketHandshakeCustomizes the initial handshake
@SocketEndpointDeclares a per-session WebSocket handler class
SocketSession (injected)Allows sending messages, pinging, and closing

© 2026 Fluxzero