Upload
julien-lapointe
View
230
Download
4
Embed Size (px)
Citation preview
WebSocketsJulienLaPointe
WhatisaWebSocket?
• Communicationprotocolusedtosend/receivedataontheInternet• LikeHTTP,butonsteroids...WebSocketsarewayyymoreefficient• Persistent2-way connectionbetweenbrowser<-->server• Easytobuildreal-time applications:• Chat• Notifications• Onlinegames• Financialtrading• Datavisualizationdashboards• Livemaps• Collaborationapps
Half-duplex(likewalkie-talkie) Full-duplex(likephone)Trafficflowsin1directionatatime Bi-directionaltrafficflow
HTTP WebSocket
Rogerthat.Overandout...
...Who’sRoger? IknoooowwRight??!!!
Liketotalllyyyy
Forreal??
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
LifeBeforeWebSockets...
Arewethereyet?
Arewethereyet?Arewe
thereyet?
Arewethereyet?Arewe
thereyet?
• Simulatereal-timecommunicationwith HTTP• AJAX: browsersendsrequestsatregularintervalstocheckforupdatesbutheaderscauselatencyandpollingisveryresourceintensive• Comet:serverpushtechniquebutcomplex,non-standardizedimplementation• Streaming:moreefficientthanAJAXandCometbutonly1direction
HowdoWebSocketswork?
HerokuServer
YourPhone
YourComputer
1. ClientsendsHTTPGETrequesttoURL(https://socketio-experimentia.herokuapp.com/)
HowdoWebSocketswork?
HerokuServer
YourPhone
YourComputer
2. Serverrespondswithrequestedfiles,whichincludeinformationforconnectingtosocketserver
1. ClientsendsHTTPGETrequesttoURL(https://socketio-experimentia.herokuapp.com/)
HowdoWebSocketswork?
HerokuServer
YourPhone
YourComputer
2. Serverrespondswithrequestedfiles,whichincludeinformationforconnectingtosocketserver
1. ClientsendsHTTPGETrequesttoURL(https://socketio-experimentia.herokuapp.com/)
3. ClientsendsHTTPGETrequestwith“Connection:Upgrade”intheheader,serverconfirmssupport,andconnectionisupgradedtoWebSockets(calledthe“handshake”)untilonesidedisconnects
IsthereANYTHING badaboutWebSockets?
• NotallbrowserssupportWebSockets• DifferentbrowserstreatWebSocketsdifferently
ReleasedMarch8,2017
FirstsupportedMarch2,2016
SupportasofMarch8,2017
Socket.io
• 2JavaScriptlibraries:• socket.io-client(front-end)• socket.io (back-endusingNodeJS)
• Cross-browsercompatibilitybyautomaticallyusingthebestprotocolfortheuser’sbrowser• WebSockets• Comet• Flash
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
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
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
Socket.ioDemo
• Socket.io,Express/NodeJS,React,D3,Bootstrap,Webpack• Lynda.com:BuildingaPollingAppwithSocketIOandReact.js
Questions?
Pickme!
Pickme!
Pickme!
Pickme!
Pickme! Pickme!Pickme!
Pickme!
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/