Intro to Web Sockets

using Node JS & Socket.IO

By Michael Mottola

What are Web Sockets?

Web Sockets...

  • were developed as HTML5 initiative
  • is a full-duplex single TCP socket connection
  • provides "realtime" communication between
    servers and clients
  • works consistently across multiple platforms
  • supports cross domain communication
  • does not make AJAX obsolete

Use Cases

  • Multiplayer online games
  • Chat applications
  • Live sports ticker
  • Realtime updating social streams

Server Side Implementations

http://socket.io

Installing Socket.io


npm install socket.io
						
Server Side JavaScript

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

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
							
Client Side JavaScript



							

Socket.io using Express Web Framework


var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(80);

app.get('/', function (req, res) {
  res.render('home');
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
}); 
						

Sending a Broadcast


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

io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});
						

Sending Volatile Messages


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

io.sockets.on('connection', function (socket) {
  var tweets = setInterval(function () {
    getFancyTweet(function (tweet) {
      socket.volatile.emit('fancy tweet', tweet);
    });
  }, 100);

  socket.on('disconnect', function () {
    clearInterval(tweets);
  });
});
							

Example App

My Test Run with Socket.io

Football Pong

Full Field
Field Goal Position
Endzone
Field Goal

Football Pong Scoreboard

https://github.com/controlz/Football-Pong-Scoreboard
Scoreboard

Learn more about sockets

THE END

Thanks for Viewing

- Michael Mottola