Broadcasting to a subset of subscribers in Atmosphere

我与影子孤独终老i 提交于 2019-12-04 15:51:56

If I understand your requirements correctly the following should work (jax-rs + scala code):

1) Everyone who wants to get messages from a chat room registers for it:

@GET
@Path(choose/a/path)
def register(@QueryParam("chatroomId") chatroomId: Broadcaster) {
  // alternatively, the Suspend annotation can be used
  new SuspendResponse.SuspendResponseBuilder[String]()
          .resumeOnBroadcast(false).broadcaster(chatroomId).scope(SCOPE.REQUEST)
          .period(suspendTimeout, TimeUnit.MINUTES)
          .addListener(new AtmosphereEventsLogger()).build
}

2) To broadcast a message for all the registered users, call the following method:

@POST
@Broadcast
@Path(choose/a/path/{chatroomId})
def broadcast(@PathParam("chatroomId") id: String) {
  // first find your broadcaster with the BroadcasterFactory
  BroadcasterFactory.getDefault().lookupAll() // or maybe there is a find by id?
  broadcaster = ...
  broadcaster.broadcast(<your message>)
}

I also recommend reading the atmosphere whitepaper, have a look at the mailing list and at Jeanfrancois Arcand's blog.

Hope that helps.

There is a misunderstaning of the concept of comet. Its just another publish/subscribe implementation. If you have multiple chat-rooms, then you need to have multiple "topics", i.e. multiple channels the user can register to. E.g.:

broadcaster['/atmosphere/chatRoom1'].broadcast('Hello world!')

broadcaster['/atmosphere/chatRoom2'].broadcast('Hello world!')

So I would advance you to creaet multiple channels and do not filter manually the set of users, which should retrieve messages (which is definitely not the way it should be done). You do not need to create anything on the server side on this, since the user will just register for a specific channel and receive messages, which anyone is putting into it.

I would recommend you create an AtmosphereHandler for one URL like /atmosphere/chat-room and then use the AtmosphereResource and bind an BroadcastFilter with it, lets say name it ChatRoomBroadcastFilter.

Whenever a user subscribes to a new chat room, a message would be sent to the server (from the client) telling the server about the subscription. Once subscribed, maintain the list of users <> chat room bindings somewhere on the server.

Whenever a message is broadcasted, broadcast it with the chat room id with it. The in the ChatRoomBroadcastFilter (You probably need to make this a PerRequestBroacastFilter) propagate the message to the user only if the user subscribed to the chat room. I am not sure if this clears it out. If you need code example please mention in the comments. I'll put that but that needs some time so ain't putting it right now ;).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!