WebSockets 

the right way



Julián David Duque
Developer by Passion
Engineer at Nodejitsu

http://about.me/julianduque - @julian_duque



Raw WebSockets

RFC-6455


Demo - Server

$ npm install ws
$ cat > server.js
var wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function (ws) {
  ws.send('Hello from WS Server');

  ws.on('message', function (msg) {
    console.log('Received: ' + msg);

    if (msg == "hello") {
      ws.send("Hello from server!");
    }

  });
});
$ node server.js


Demo - Client

var ws = new WebSocket('ws://localhost:8080');

ws.onopen = function () { console.log('Connected')  };
ws.onerror = function (err) { console.log(err) }; ws.onmessage = function (e) { console.log(e.data); };



Socket.IO

Most popular in Node.js world

Demo - Server

$ npm install socket.io$ cat > server.js
var socketio = require('socket.io');
var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-type': 'text/html' });
  fs.createReadStream('./index.html').pipe(res);
});

server.listen(8080);

var io = socketio.listen(server);

io.on('connection', function (socket) {
  socket.emit('hello', 'from server!');

  socket.on('hello', function (msg) {
    console.log('Received: %s', msg);
    socket.emit('world');
  });
}); $ node server.js


Demo - Client

<p>Let's test Socket.io</p><script src="/socket.io/socket.io.js"></script><script>
var socket = io.connect('http://localhost:8080');
socket.emit('hello', 'Hello from client!');
socket.on('hello', function (msg) {
  console.log('Received ' + msg);
});
</script>



Last commit 6 months ago!!



Engine.IO

The `core` behind Socket.IO 1.0



Sock.JS

Cross domain Connections

http://npm.im/sockjs




The Right Way?

Meet Primus!





Primus

Universal wrapper for real-time frameworks


Demo - Server

var Primus = require('primus'),
    http = require('http'),
    fs = require('fs');

var server = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  fs.createReadStream('./index.html').pipe(res);
});

var app = new Primus(server, { transformer: 'engine.io' });

app.use('emitter', 'primus-emitter')

server.listen(8080);

app.on('connection', function (socket) {
  socket.emit('hello', 'from server');

  socket.on('hello', function (msg) {
    console.log('Received: %s', msg);
  });
}); 


Demo - Client

<p>Let's test Primus!</p><script src="/primus/primus.js"></script><script>var socket = Primus.connect('http://localhost:8080')socket.on('hello', function (data) { console.log('Received: ' + data); socket.emit('hello', 'from client!');});</script>




Thank You


See you in the next Workshop: 
Real-time applications in Node.js with Primus

WebSockets the right way

By Julián Duque

WebSockets the right way

  • 3,828