ralscha / sse-eventbus

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

Using SSE with spring security #11

Closed haider-ali closed 5 years ago

haider-ali commented 5 years ago

Is it possible to keep the event emitter in session so message can be sent to specific user

ralscha commented 5 years ago

I guess this could work, then you no longer need this library. How do you access the sessions?

haider-ali commented 5 years ago

Actually i have a scenario where instead of pushing notification to all the user i have to push only to specific user for for that either i have to put it in session or static map with key as username , for session i was think creating a custom userprinciple class and on SSE connection updating that userpricple , when on server side i can iterate on all the users that are currently online and get appropriate emitter to push notification

ralscha commented 5 years ago

In that case you don't need the library, because your application manages all the SseEmitter instances.

If you want to use the library you could follow this approach. When a client registers, instead of just subscribing him to the default event your application subscribes him to an event that is unique for this particular user. For example the user id or username or something else that is unique.

    @GetMapping("/register/{id}")
    public SseEmitter register(@PathVariable("id") String id) {     
                userIdentification = // user id or username of logged in user
                // subscribe this user to the default topic and to a special user topic
        return this.eventBus.createSseEmitter(id, SseEvent.DEFAULT_EVENT, userIdentification );
    }

Then, from other parts of the application you can send an event to one particular user

// sending message to one user 
userIdentification = ....
this.eventBus.handleEvent(SseEvent.of(userIdentification, some_data));

The tricky part is on the client where you have to add an event listener for this special topic. Unfortunately the message event only catches messages sent to the default topic. Somehow the client needs to know the unique identification of the user

const specialUserTopic =  // same as userIdentification  on the server
const uuid = uuid();
const eventSource = new EventSource(`/register/${uuid}`);
eventSource.addEventListener(specialUserTopic, response => {
    //handle the response from the server
}, false);