Interface HandshakeResult

All Known Implementing Classes:
HandshakeResult.Accepted, HandshakeResult.Rejected

Represents the result of a ServerSentEventSource "handshake".

Once a handshake has been accepted, you may acquire a broadcaster via ServerSentEventServer.acquireBroadcaster(ResourcePath) - the client whose handshake was accepted will then receive Server-Sent Events broadcast via ServerSentEventBroadcaster.broadcastEvent(ServerSentEvent).

You might have a JavaScript Server-Sent Event client that looks like this:

// Register an event source
let eventSourceUrl =
  'https://sse.example.com/chats/123/event-source?signingToken=xxx';

let eventSource = new EventSource(eventSourceUrl);

// Listen for Server-Sent Events
eventSource.addEventListener('chat-message', (e) => {
  console.log(`Chat message: ${e.data}`);
});

And then a Soklet Server-Sent Event Source that looks like this, which performs the handshake:

// Resource Method that acts as a Server-Sent Event Source
@ServerSentEventSource("/chats/{chatId}/event-source")
public HandshakeResult chatEventSource(
  @PathParameter Long chatId,
  @QueryParameter String signingToken
) {
  Chat chat = myChatService.find(chatId);

  // Exceptions that bubble out will reject the handshake and go through the
  // ResponseMarshaler.forThrowable(...) path, same as non-SSE Resource Methods
  if (chat == null)
    throw new NotFoundException();

  // You'll normally want to use a transient signing token for SSE authorization
  myAuthorizationService.verify(signingToken);

  // Accept the handshake with no additional data
  // (or use a variant to send headers/cookies).
  // Can also reject via HandshakeResult.rejectWithResponse(...)
  return HandshakeResult.accept();
}

Finally, broadcast to all clients who had their handshakes accepted:

// Sometime later, acquire a broadcaster...
ResourcePath resourcePath = ResourcePath.fromPath("/chats/123/event-source");
ServerSentEventBroadcaster broadcaster = sseServer.acquireBroadcaster(resourcePath).orElseThrow();

// ...construct the payload...
ServerSentEvent event = ServerSentEvent.withEvent("chat-message")
  .data("Hello, world") // often JSON
  .retry(Duration.ofSeconds(5))
  .build();

// ...and send it to all connected clients.
broadcaster.broadcastEvent(event);

Full documentation is available at https://www.soklet.com/docs/server-sent-events.

Author:
Mark Allen