简体   繁体   中英

Socket.io: How to make everyone get a different channel?

I'm currently developing a little website, and i want to make everyone listen to a different channel because it's like a website that search something server side then reply to the client. The only idea I have in mind is something like this:

Client Side:

var randomnum = Math.floor((Math.random() * 100) + 1);
socket.emit('getnumber', randomnum);
// Then listen to that channel for incoming stuff
socket.on(randomnum, function(msg){
[...]

Server Side:

socket.on('randomnum', function(randomnumget){
// Do things with it then
[...]
socket.emit('getnumber', 'stuff');
});

But doing this for more than 4 will be kind of hard, i'm sure there's another easy way to do it! Thanks you

here is my possible implementation idea/flow. Currently, it's unknown what load your application needs to be handle so the end implementation might need to be improved.

I assume that you identify your users with some sort of ID, store it in cookie or localstorage.

First, when the user visits your site, it requests the socket channel to connect(example GET /channel). On server-side you implement the query which gives each user unique ID, it could be UUID or some other time-based id. To make sure the users won't get exactly the same ID, you could store IDs in Redis or in some other DB.

Additionally, you could use Redis key EXPIRE to remove the key from DB after 10 minutes for an example.

Using the random numbers like in your example isn't the best option as it tends to collide pretty quickly. For example to get better unique channels names you could do: sha256(Date.now() + Math.random()) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM