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 linessocket.io on the other hand is a C node.js plugin and 61000 lines of JS code :(
// 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)
See, for example, https://github.com/Automattic/socket.io-client/issues/572 (closed without comment).
If you want a nice websockets library that handles old browsers, use SockJS. It's far better.
[edit: fixed a silly typo]
If your language of choice has a SockJS implementation, I'd recommend it as a first option.
Also, magically trying to decode strings if they look like JSON sounds rather scary.
That's not what's going on. Each message is tagged with a "type", and one of the tags means "JSON.parse this into an object" while another means "this is just a string".
The rest of the types are for control messages (like ping/pong), I believe.
socket.emit("hello"); and the server can listen on this event with socket.on("hello"). If you want to do the same thing with the reference WebSocket you have to re-implement the same thing again and you will probably end up recoding the wrapper that socket.io already gives you.