Hacker News new | ask | show | jobs
by greggman 4082 days ago
> If you send json over the wire, socket.io automatically converts it to a javascript object or array for you, ready to be used.

That's literally 4 lines

    // sender
    ws.send({event: JSON.stringify(someObject));

    // receiver
    ws.on('message', function(str) {
       obj = JSON.parse(str);
    });
> socket.emit("hello"); and the server can listen on this event with socket.on("hello").

This is hardly any more lines of code

    // sender
    function sendEvent(eventName, data) {
      ws.send(JSON.stringify({event: eventName, data: data}));
    }

    // receiver
    ws.on('message', function(str) {
      var eventInfo = JSON.parse(str);
      eventEmittier.emit(eventInfo.event, eventInfo.data);
    });

Sure I'm glossing over a few things but EventEmitter is 10-20 lines depending on how crazy you want to get and wrapping both in a objects is probably another 10-20 lines

socket.io on the other hand is a C node.js plugin and 61000 lines of JS code :(

3 comments

Socket.IO also gives you things like cross-everything callbacks:

     // server
     io.emit('event', function (msg) { console.log('Client responded!', msg) })

     // client
     io.on('event', function (cb) { cb('This is my response') })
And it also provides socket namespacing, and "rooms" (a bit like chat rooms), and broadcasts, and a bunch of things that I don't use.

Sure, you can bolt all of that on in probably a few hundred lines, but socket.io also doesn't just do sockets and events :)

(And it also does it in less than 61000 lines. You still need the "ws" module to do WebSocket stuff in Node, even if you don't use socket.io)

Socket.io also transparently handles sessioning and resuming of sessions (automatic reconnect), namespaces, filters, and a ton of other useful stuff for a moderately-complex application. If I'm just sending events between client and server (say, live-updating a common twitstream), regular ws is fine. But if I'm selecting and reflecting certain events to other connected clients by room, and don't want to worry about stuff like "oh hey, that guy needs to re-handshake because he lost network", socket.io provides a lot of useful sugar.
You don't even need an event emitter. In many cases you might just use switch(){}.