上QQ阅读APP看书,第一时间看更新
How it works...
This recipe is made up of three parts:
- The server, represented by the ServerMock class
- The SSE engine, represented by the SseResource class
- The client, represented by the ClientConsumer class
So once ServerMock is instantiated, it registers the SseResource class:
final ResourceConfig resourceConfig = new ResourceConfig(SseResource.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(CONTEXT, resourceConfig, false);
server.start();
Then two key methods from SseResource take place. The first one adds messages to the server queue:
addMessage(final String message, @Context Sse sse)
The second one consumes this queue and sends the messages to the clients:
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void getMessageQueue(@Context SseEventSink sink)
Note that this one has a media type SERVER_SENT_EVENTS, introduced in this version for this very purpose. And finally, we have our client. In this recipe, it is both posting and consuming messages.
It consumes here:
sseSource.register(System.out::println);
sseSource.open();
It posts here:
ServerMock.WEB_TARGET.request().post(Entity.json("event " + innerCounter));