peter flanagan
peter flanagan

Reputation: 9790

Websocket dealing with different data - different endpoints?

I am curious about websockets and how to distinguish different data that it sends. I cannot really find anything clear online either, unless I am missing something that is staring me in the face.

I have a websocket and the handshake establishes the connection. The purpose of the ws is going to provide live football scores, and a live table.

So if it was a rest API I would probably have 2 endpoints, /live-scores and /table. My react components are interested in different data so I am wondering if there is an equivalent of endpoints in web sockets? Or how do you differentiate between different data? Should there be a separate web socket for each piece of data?

Also, bear in mind there will be a lot more than 2 pieces of data besides live scores and table so I am thinking a different ws for each would be overkill.

Can anyone point me in the right direction or provide an answer here?

TLDR Do you create a websocket for each different group of data (for want of a better way of describing this) or is there just one websocket and if so what is the best way for the client to distinguish what kind of data it is receiving?

If the question makes no sense let me know and I will try and make it clearer.

My starting code is here:

import sockjs from 'sockjs';

const ws = sockjs.createServer({
    sockjs_url: 'http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js',
});

ws.on('connection', connection => {
    connection.on('data', m => {
        const message = m ? JSON.parse(m) : {};
        if (message.type === 'register') {
            connection.write(
                JSON.stringify({
                    address: message.address,
                    body: {
                        message: 'Hello World!',
                    },
                })
            );
        }
    });
});
export default ws;

Upvotes: 1

Views: 1937

Answers (1)

Besworks
Besworks

Reputation: 4483

You shouldn't need to use multiple sockets to do what you want. There are actually only a few legitimate reasons why you might want to so (see Multiple websocket connections).

Your method of sending JSON payloads over the socket and using a property of that object to determine the context of the data is perfectly acceptable however you might want to do a little research into the publish-subscribe messaging pattern to see if it would suit your needs better. Since you're using sockjs you would want to look at sockjs-rooms to enable this type of functionality.

Upvotes: 1

Related Questions