4. WebSockets
What?
● A persistent connection between the client and the server
● Both parties can start sending data at any time
Why?
● Low-latency communication
● Bi-directional communication
● Performances
6. Polling vs WebSockets
Polling WebSockets
Connections multiple single
Communication client-to-server bi-directional
Latency high low
Cost high, both for server and client low
7. Socket.IO
What?
● Realtime application framework
● Wrapper around Websockets (browser + Node.js)
● Send events between the client and the server
Why?
● Fallback for old browsers (IE8+)
● JavaScript, Android, iOS clients
● Trivial APIs
8. Setup
Server side: Client side:
user ~ $ npm install --save socket.io
// import socket.io
const socket = require('socket.io');
// attach socket.io an http server
var io = socket().listen(httpServer);
// listen for connections
io.on('connect', function (socket) {
// listen for events
socket.on(‘event’, function (data) {
// reply to events
io.emit(‘other-event’, data);
});
};
<!-- include socket.io -->
<script src="/socket.io/socket.io.js"></script>
// create socket.io instance
var socket = io();
// connected to the server
socket.on('event', function (msg) {
console.log(msg);
});
9. Server API
Server:
● io.on(‘connection’, callback(socket)) - new connected client
Socket:
● socket.on(event, callback(data)) - attach a new listener for the given event
● socket.emit(event, data) - send the event to this client
● socket.broadcast.emit(event, data) - send the event to all clients
10. Client API
Socket
● socket.on(event, callback(data)) - attach a new listener for the given event
● socket.emit(event, data) - send the event to the server
… yes, that’s it!