Atmosphere + Jersey: How do I have several broadcasters?

I have a working Jersey / Atmosphere / Guice app that has two Atmosphere Resources in it. The first is more of a clone of the chat application example:

@Path("/chat") @AtmosphereService(broadcaster = JerseyBroadcaster.class, path = "/chat") public class ChatResource { @Suspend(contentType = "application/json") @GET public String suspend() { return ""; } @Broadcast(writeEntity = false) @POST @Produces("application/json") public Response broadcast(Message message) { return new Response(message.author, message.message); } } 

The second test notification resource that will be sent to server events:

 @Path("/notifications") @AtmosphereService(broadcaster = JerseyBroadcaster.class, path = "/notifications") public class NotificationsResource { @Suspend(contentType = "application/json") @GET public String suspend() { return ""; } } 

Everything is correctly connected and works fine. However, so that I can send an event on the server side, I output:

 MetaBroadcaster.getDefault().broadcastTo("/*", new Response(...)); 

Obviously, this will send a broadcast message to both resources. What I want to do is send events on the server side only to the notification resource:

 MetaBroadcaster.getDefault().broadcastTo("/notifications", new NotificationResponse(...)); 

However, this does not work. I always get the following error:

 org.atmosphere.cpr.MetaBroadcaster - No Broadcaster matches /notifications. 

This is because only one broadcaster is registered; the JerseyBroadcaster on / *.

Question: how can I make these two resources have different broadcasting companies with different identifiers / names?

+4
source share
2 answers

In the resource, suspend the use of the desired channel (the "true" parameter for search () forces the channel to be created if it does not exist):

 @Suspend( contentType = MediaType.APPLICATION_JSON, period = MAX_SUSPEND_MSEC ) @GET public Broadcastable suspend( @Context final BroadcasterFactory factory ) { return new Broadcastable( factory.lookup( MY_CHANNEL, true ) ); } 

In another code, which can be almost anywhere, it is broadcast on this channel:

 Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup( MY_CHANNEL ); if( broadcaster != null ) { broadcaster.broadcast( message ); } 

If you intend to broadcast using the resource method, you can annotate it instead (as shown in the ChatResource broadcast () method).

+7
source

Just enter Broadcaster using the @PathParam annotation:

 private @PathParam("topic") Broadcaster topic; 

You can also use the @Context annotation. Hope that helps.

- Jeanfrancois

+2
source

Source: https://habr.com/ru/post/971070/


All Articles