Socket.io

by Severin Ibarluzea and Joey Lee

Socket.io

  • Node.js
  • Real-time web communication
  • Faster than polling
  • Simple API

Polling?

Querying web server constantly for new data

// Constantly query web server for updates
setInterval(function(){
    $.ajax({ url: '/mypage', success: function(data){
        // Do stuff with message
    } });
}, 100);

Long Polling

function load(){
    $.ajax({ url: '/mypage', success: function(){
        // do something with the data
    }, complete: load, timeout: 20000 });
}

The Problem

Polling is slow

Simulating sockets from scratch is tricky

Easy configuration

Easy to use server

Installation

npm install socket.io

Getting Connected

var socket = io.connect('http://server.com/');
socket.on('news', function (data) {
    // Do stuff with data
});
<script src="socket.io.js"></script>

CDN: https://cdn.socket.io/socket.io-1.2.0.js

The Server

// server is an express/http server
var io = require('socket.io')(server);

io.on('connection', function (socket) {
    socket.on("message", function(data){});
    socket.on('disconnect', function () {});
});

The Basics

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    // Do stuff with data
  });
</script>

Client

Server

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

io.on('connection', function (socket) {
  socket.emit('news', "Hello World!");
});

Chatroom

Client

Server

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
  console.log("User Connected!");
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

// (also do some stuff to serve the client)
var socket = io();
$('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
});
socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
});

Chatrooms are boring

Let's make a game

Wait but I use PHP

Let's talk about the real problem

WebSockets are still great

http://socketo.me/

jk, Cross-domain socket.io

Thank You

RCOS

Professor Goldshmidt

Professor Moorthy

Sean O'Sullivan

Made with Slides.com