Intro to Web Sockets
-
Upload
jim-gourgoutis -
Category
Technology
-
view
1.202 -
download
1
Transcript of Intro to Web Sockets
INTRODUCTION TO WEBSOCKETS
WebSockets are a new way to connect clients and servers with efficient two-way
communication that allows us to build true desktop-style web applications!
HTTP Protocol
• High Overhead (request & response headers, cookies, etc.)
• “Half-duplex” connection (request/response)
Current Workarounds
• AJAX/XHR– Content can update w/o full page refresh– User-perceived low latency– Faux real-time via polling/long-polling
• Comet– No standard specification– Very complex to implement
WebSocket Advantages!
• Full-duplex, low overhead• Direct connection between client &
server• Same ports as HTTP/HTTPS• Based on Web Standards (W3C &
IETF)• Unlike XHR, it works cross-domain!
WebSocket APIvar ws = new WebSocket(url);ws.onopen = function (evt) { /*
connection open */ };ws.onmessage = function (evt) { /*
received message */ console.dir(evt.data); };
ws.onclose = function(evt){ /* connection closed */ };
WebSocket API (ctd)// Send a messagews.send(“Do you like the scary
clowns?!?”);
// Close the connectionws.close();
Not Like WebSockets!
• Not two-way, just push from server• Uses plain-ol’ HTTP• Different message transport
mechanism• Same-origin policy applies.
EventSource API
var es = new EventSource(url);es.readyState property 0 = connecting,1 = open, 2 = closedes.close() closes the connection
EventSource Events
es.onopen = function(evt){};es.onmessage = function(evt){};es.onerror = function(evt){};es.addEventListener();
Data object: evt.data
Sending Messages
• MIME type = text/event-stream• Plain-text format• id: message; id defaults to “data” if
not specified• New lines (\n) are significant
SUPER-AWESOME WEBSOCKET CHAT DEMO
I built a web chat application using WebSocket and EventSource. Oh, and some Node.js and Socket.io, too.http://jgourgou-mn.linkedin.biz:8080/
Take-Aways
• Socket.io is to WebSockets as Jquery is to DOM
• Socket.io documentation sucks.• Web examples for Socket.io suck.• Node.js is weirdly cool, and
overwhelming in a Java sort of way.
Resources/Further Reading
• http://www.slideshare.net/pmoskovi/building-living-web-applications-with-html5-websockets
• http://howtonode.org/websockets-socketio
• https://github.com/LearnBoost/socket.io• http://www.websocket.org/• http://www.nczonline.net/blog/2010/10/1
9/introduction-to-server-sent-events/• https://github.com/remy/eventsource-h5
d• http://www.html5rocks.com/en/tutorials/
eventsource/basics/• http://html5doctor.com/server-sent-
events/