JavaScript technologies

Live applications with Websockets

Horváth, Győző
senior lecturer
horvath.gyozo@inf.elte.hu

Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government

Live applications

WebSockets

HTTP limitations

  • Request-response
  • Client starts the communication
  • No server push
  • A lot of unnecessary data (e.g. headers)

Websocket protocol

Standard

Two-way persistent connection between the client and the server.

Socket.io

High-level library over Websocket protocol with fall-back mechanisms.

Client and server side library

Project

Installation

npm install --save socket.io

Usage (server)

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

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
    console.log(socket.id);
});

Usage (client)

<!doctype html><title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost');

    socket.on('something', function (isPresenter) {
        doSomething();
    });
    
    function doSomething() {
        socket.emit('resp', 'hello');
    }
</script>