Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io broadcast from client

Tags:

I just started with socket.io, and I want some function which will broadcast somethink from one client throuh server to all clients.

For example I will have game, when I will need handle a lot of things.

There is two option: 1. Every call handle on server and client side, for every call create socket.on('call');

But I think there is better solution 2. On client call emit when I get payload and name of socket which will be called from server to other clients.

Like this: SERVER

// Broadcast specific emit to all clisnts expect sender
socket.on('broadcast', function(data){
    socket.broadcast.emit(data.emitName, {id: socket.id, payload: data.payload});
});

and client:

// Call to server
socket.emit('broadcast', {emitName: 'playerMove', payload: {....}});

// Handle called from server
socket.on('playerMove', function(data){
   ....
});

Second solution can save a lot of time, but is it safe solution ? And is there any better solution how call from client broadcast throuht server and call to other clients ?

like image 778
Hadik Avatar asked Apr 01 '16 09:04

Hadik


1 Answers

Only the server can broadcast to all clients. The server retains control. Your second solution is the best solution.

You may want to somehow ensure that you trust the client that is making the emit that will result in the broadcast. HTTP protocol is well-established in respect of client authentication.

Websockets does not have the same standard approach. Maybe you should investigate Websocket client authentication. There is no reason why you cannot use JWT authentication with websockets, just send the JWT token in the data packet the client is sending. This is probably how I would handle authentication but I am no expert on how to do this with websockets.

like image 179
danday74 Avatar answered Oct 11 '22 12:10

danday74