16
WebSockets Julien LaPointe

Introduction to WebSockets Presentation

Embed Size (px)

Citation preview

Page 1: Introduction to WebSockets Presentation

WebSocketsJulienLaPointe

Page 2: Introduction to WebSockets Presentation

WhatisaWebSocket?

• Communicationprotocolusedtosend/receivedataontheInternet• LikeHTTP,butonsteroids...WebSocketsarewayyymoreefficient• Persistent2-way connectionbetweenbrowser<-->server• Easytobuildreal-time applications:• Chat• Notifications• Onlinegames• Financialtrading• Datavisualizationdashboards• Livemaps• Collaborationapps

Page 3: Introduction to WebSockets Presentation

Half-duplex(likewalkie-talkie) Full-duplex(likephone)Trafficflowsin1directionatatime Bi-directionaltrafficflow

HTTP WebSocket

Rogerthat.Overandout...

...Who’sRoger? IknoooowwRight??!!!

Liketotalllyyyy

Forreal??

Page 4: Introduction to WebSockets Presentation

Half-duplex(likewalkie-talkie) Full-duplex(likephone)Trafficflowsin1directionatatime Bi-directionaltrafficflowConnectionistypicallycloses after1request/responsepair

Connectionstaysopen

1.Request fromclient toserver2.Response fromservertoclient

Bothclientandserveraresimultaneously “emitting”and“listening”(.onevents)

Headers(1000s ofbytes) Uses“frames”(2bytes)150ms toestablishnewTCPconnectionforeachHTTPmessage

50ms formessagetransmission

Pollingoverhead(constantlysendingmessages tocheckifnewdataisready)

Nopollingoverheard(onlysendsmessageswhenthereisdatatosend)

HTTP WebSocket

Page 5: Introduction to WebSockets Presentation

LifeBeforeWebSockets...

Arewethereyet?

Arewethereyet?Arewe

thereyet?

Arewethereyet?Arewe

thereyet?

• Simulatereal-timecommunicationwith HTTP• AJAX: browsersendsrequestsatregularintervalstocheckforupdatesbutheaderscauselatencyandpollingisveryresourceintensive• Comet:serverpushtechniquebutcomplex,non-standardizedimplementation• Streaming:moreefficientthanAJAXandCometbutonly1direction

Page 6: Introduction to WebSockets Presentation

HowdoWebSocketswork?

HerokuServer

YourPhone

YourComputer

1. ClientsendsHTTPGETrequesttoURL(https://socketio-experimentia.herokuapp.com/)

Page 7: Introduction to WebSockets Presentation

HowdoWebSocketswork?

HerokuServer

YourPhone

YourComputer

2. Serverrespondswithrequestedfiles,whichincludeinformationforconnectingtosocketserver

1. ClientsendsHTTPGETrequesttoURL(https://socketio-experimentia.herokuapp.com/)

Page 8: Introduction to WebSockets Presentation

HowdoWebSocketswork?

HerokuServer

YourPhone

YourComputer

2. Serverrespondswithrequestedfiles,whichincludeinformationforconnectingtosocketserver

1. ClientsendsHTTPGETrequesttoURL(https://socketio-experimentia.herokuapp.com/)

3. ClientsendsHTTPGETrequestwith“Connection:Upgrade”intheheader,serverconfirmssupport,andconnectionisupgradedtoWebSockets(calledthe“handshake”)untilonesidedisconnects

Page 9: Introduction to WebSockets Presentation

IsthereANYTHING badaboutWebSockets?

• NotallbrowserssupportWebSockets• DifferentbrowserstreatWebSocketsdifferently

ReleasedMarch8,2017

FirstsupportedMarch2,2016

SupportasofMarch8,2017

Page 10: Introduction to WebSockets Presentation

Socket.io

• 2JavaScriptlibraries:• socket.io-client(front-end)• socket.io (back-endusingNodeJS)

• Cross-browsercompatibilitybyautomaticallyusingthebestprotocolfortheuser’sbrowser• WebSockets• Comet• Flash

Page 11: Introduction to WebSockets Presentation

Socket.io ServerConfiguration// add the HTTP server

var http = require('http');

// add Express server framework for NodeJS

var express = require('express');

// add Socket.io server framework

var socketIO = require('socket.io');

// create instance of Express

var app = express();

// create Express HTTP server

var server = http.createServer(app);

// tell Express HTTP server which port to run on

server.listen(8080);

// tell Socket.io to add event listeners to Express HTTP server

var io = socketIO().listen(server);

1.CreateHTTPserver

2.AddWebSocketsupporttoHTTPserver

Page 12: Introduction to WebSockets Presentation

Socket.io ServerCode// listens for new socket connections from clients

// triggers a callback function when ‘connection’ event occurs

io.sockets.on('connection', function(socket) { // do stuff (ex. keep track of # of socket connections)

connections.push(socket);

// emit / broadcast custom event and data (payload) to client

io.sockets.emit(’updateStudents', payload);}

// listen for custom events “emitted” by client

socket.on('join', function(payload) { var newStudent = {

socketID: this.id,

name: payload.name

}

this.emit('joined', newStudent);}

1.Listen

2.Emit

1.Listen

2.Emit

Page 13: Introduction to WebSockets Presentation

Socket.io ClientCode// add Socket.io client framework

var io = require(’socket.io-client');

// add Socket.io client framework

this.socket = io('http://localhost:3000');

// listen for socket connection from server

this.socket.on(’connect', function() {var newStudent = {name: nameFromForm, type: “student”};

// emit custom event with data (newStudent) back to server

this.emit('join', newStudent);}

// listen for custom events with data (payload) “emitted” by server

this.socket.on('joined', function(payload) { // do stuff with payload...

}

1.Listen

2.Emit

Page 14: Introduction to WebSockets Presentation

Socket.ioDemo

• Socket.io,Express/NodeJS,React,D3,Bootstrap,Webpack• Lynda.com:BuildingaPollingAppwithSocketIOandReact.js

Page 15: Introduction to WebSockets Presentation

Questions?

Pickme!

Pickme!

Pickme!

Pickme!

Pickme! Pickme!Pickme!

Pickme!

Page 16: Introduction to WebSockets Presentation

KeyReferences

• https://www.lynda.com/Web-Development-tutorials/Building-Polling-App-Socket-IO-React-js/387145-2.html• https://socket.io/get-started/chat/• http://www.jonahnisenson.com/what-are-websockets-and-why-do-i-need-socket-io/• https://nodesource.com/blog/understanding-socketio/• http://enterprisewebbook.com/ch8_websockets.html• http://blog.teamtreehouse.com/an-introduction-to-websockets• https://www.pubnub.com/blog/2015-01-05-websockets-vs-rest-api-understanding-the-difference/