alexandrevicenzi / go-sse

Server-Sent Events for Go
MIT License
172 stars 40 forks source link

Multiple open tabs communicating #22

Closed siredwin closed 4 years ago

siredwin commented 4 years ago

I have a situation where multiple tabs are communicating with the same server individually. How do I make sure that each tab gets the right responses? The only thing I know is a dynamically generated tab id.

alexandrevicenzi commented 4 years ago

Your question does not make a lot of sense. Each tab will be an individual connection, there's no sharing of resources, each tab is a new socket.

There are two things that you can do this way:

If you want the same messages use the same channel.

e = new EventSource('/events/shared-channel');
e.onmessage = function(event) {
    console.log(event.data);
};

If you want to send a set message per-tab use a different channel per tab.

var tabId = sessionStorage.tabID;
e = new EventSource(`/events/channel-{tabId}`);
e.onmessage = function(event) {
    console.log(event.data);
};

The above code is just an example, it may not work.

siredwin commented 4 years ago

I tried your second example and it did not work. I ended up converting the payload message into a JSON string with both the message and tab id and it is working. I am only listening to one channel Let me know if this approach is ok?

alexandrevicenzi commented 4 years ago

If you have multiple channels you need to publish the message on multiple channels in the server side as well.