ralscha / sse-eventbus

EventBus library for sending events from a Spring appliction to the web browser with SSE
Apache License 2.0
79 stars 26 forks source link

SSE to a single Client #4

Closed jimmychung98 closed 6 years ago

jimmychung98 commented 6 years ago

Is there a way to send an event to a specific User? I can see that it sends an event to all subscribed users but is there a way to find the user with an id and send that user an event?

ralscha commented 6 years ago

Hi An easy way to do that is subscribing the user to an event that is unique for this user. For example if you have an user entity in your application, the application could subscribe to the primary key of this table

this.eventBus.createSseEmitter(clientId, primaryKeyOfUser);
this.eventPublisher.publishEvent(SseEvent.of(primaryKeyOfUser, data));

This has the additional benefit that when the same user is subscribed on multiple devices he would receive the message on all of them.

Another way is to use the clientId as event if you want to target one specific device.

this.eventBus.createSseEmitter(clientId, clientId);
ralscha commented 6 years ago

I forgot the most obvious solution :-) You can specify client ids that should receive the message when you construct the SseEvent.

SseEvent.builder().data("data").addClientId(clientId).build()

Only client with id clientId will receive this message


Similarly you can exclude client ids from receiving a message

SseEvent.builder().data("data").addExcludeClientId(clientId).build()

Client with id clientId will not receive this message

jimmychung98 commented 6 years ago

This works! Thank you!

adamrichman1 commented 6 years ago

Hey @ralscha , I'm working with @jimmychung98 on this and we're having some issues. For some reason when we register clients under a unique clientId, the SSE isn't sent to the client.

We register a client as follows:

this.eventBus.createSseEmitter(id, primaryKeyOfUser);

Our implemented publishEvent() method calls:

eventBus.handleEvent((SseEvent) event);

and the event is created using SseEvent.of(primaryKeyOfUser, data), as you described above. We can't figure out why it isn't finding that the users are registered to the events. Any help would be greatly appreciated.

jimmychung98 commented 6 years ago

We were able to fix this. It was a problem in our side. Sorry!