Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle when unknown socket.io event

i have following code server side.

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
  socket.on('event', function(data){
     // process...
  });
});

client side (part)

socket.emit('event', {type:'command', data:'data....'});
for (var i=0; i<=9999999; i++){
  socket.emit('unknownEvent', {'type':'attack', data:'a34tagfa3wtasfd'});
}

now, how to handle and defence 'unknownEvent' event...?..

like image 483
waitfor Avatar asked Nov 02 '22 16:11

waitfor


1 Answers

Older question, but was running into the similar thing so I figured I would share a way to do it.

Client Side

So on the client instead of passing the event as the first argument to emit, use a generic event name, like event or something. I ended up using the name of the app since it was short. Then in the data object, pass in the name of the function you want to call.

So this:

socket.emit('awesomeSocketEvent', {hello: 'world'});

Becomes:

socket.emit('genericEvent', {event:'awesomeSocketEvent', hello:'world'});

Rewriting everything on the client side sucks, and my client stuff was mostly just emit-ing so I wrapped the socket.io client in another object with it's own emit event that did the change in event names and data objects.

Server Side

Now on the server side there's only ever going to be one custom event called, genericEvent, so the custom events need to be restructured as properties of an object. Once that happens its a simple check to see if the event exists in the object, call it if it does, or do something else if it doesn't.

io.sockets.on('connection', function (socket) {

    var events = {
        awesomeSocketEvent: function(data){
            // do your socket stuff here
        }
    };

    socket.on('genericEvent', function(data){
        if(data.event in events){
            events[data.event](data);
        } else {
            // do your unknown event stuff here
        }
    });

});

After looking at the code while writing that portion, I'm not sure about performance with having the events object being declared within the connect event. It might be better to declare events outside of the connection event and then pass in socket to all of your functions.

like image 58
aron.duby Avatar answered Nov 15 '22 04:11

aron.duby