Your SlideShare is downloading. ×
0
TransformingTransformingTransforming
WebSocketsWebSocketsWebSockets
!
3rdEden
"
3rd-Eden
fb
arnout.kazemier
the good partsthe good parts
WebSocketsWebSockets
the good parts
WebSockets
Chrome 20
Firefox 12
Opera 12.1
Safari 6
Internet Explorer 10
Chrome 4
Firefox 4
Opera 11
Safari 4.2
Internet Explorer 10
oh, it’s bi-directional
&
supports binary
oh, it’s bi-directional
&
supports binary
oh, it’s bi-directional
&
supports bin...
The EndThe EndThe End
that nobody told youthat nobody told youthat nobody told you
The partsThe partsThe parts
HTTP proxy settings
in your network
settings can cause a
full browser crash.
user agent sniff
if (!
// Target safari browsers!
$.browser.safari!
!
// Not chrome!
&& !$.browser.chrome!
!
// And correct...
Writing to a closed WebSocket can
cause a full browser crash
write crash
var ws = new WebSocket("wss://localhost:8080/");!
!
ws.onmessage = function message(event) {!
// Wrap sends in...
Pressing ESC in Firefox closes the
WebSocket connection
connection end
$('body').keydown(function (e) {!
// make sure that you capture the `esc` key and!
// prevent it's default ...
Firefox can create ghost connections
when you connect during
ws.onclose.
Don’t use self signed SSL
certificates, not for development and
not in production
4G, 3G, LTE, mobile providers WTF
ARE YOU DOING?? — Reverse proxy
Virus scanners such as AVG block
WebSockets.
User, network and server firewalls
block WebSockets.
Load balancers don't understand and
block WebSockets.
So yeah.. Real-Time is HARD
What if…What if…What if…
we could change thiswe could change thiswe could change this
Frameworks!Frameworks!Frameworks!
framework
ws
https://github.com/einaros/ws/
super damned fast
supports binary
cross domain
all the cool kids are doing it
...
framework
socket.io
http://github.com/learnboost/socket.io
multiple transports
cross domain
invested with bugs
poorly / no...
framework
engine.io
http://github.com/learnboost/engine.io
supports multiple transports
cross domain
upgrade instead of do...
framework
browserchannel
https://github.com/josephg/node-browserchannel
multiple transports
client maintained by google
me...
framework
sockjs
https://github.com/sockjs/sockjs-node/
multiple transports (tons of them)
cross domain
poor error handlin...
They all have different use cases and
API's.
!
Changing product specs == rewrite
we could change this toowe could change this toowe could change this too
What if…What if…What if…
npm install primus
Primus wraps and improves popular
real-time frameworks. So you can
focus on building apps.
CommunityCommunityCommunity
community
community
1014
1
5
stars, but growing steady
star it on http://github.com/primus/primus
1014
1 line of code to switch between
exclud...
community
community
50
31
50
31
50 different plugins
substream, emit, primus-emitter, primus-cluster, primus-rooms, primus-multiplex, primus-re...
community
#primus on irc.freenode.net
questions are bugs, ask them in our github issue tracker
why was primus inventedwhy was primus inventedwhy was primus invented
HistoryHistoryHistory
history
real-time layer
for the bigpipe
app framework
history
which had an
engine.io
wrapper
history
no single point
of failure
history
extracted and
released as
!
primus
Use casesUse casesUse cases
use cases
module & framework authors
use cases
startups & web developers
Learning
Primus
Learning
Primus
Learning
Primus
learning primus
cd your-awesome-project!
!
$ npm install --save primus ws!
!
echo "??" !
echo “profit!”!
!
vim index.js
learning primus
'use strict';!
!
var Primus = require("primus")!
, server = require("http").createServer(fn)!
, primus = n...
learning primus
<script src="http://localhost:8080/primus/primus.js"></script>!
<script>!
'use strict';!
!
var primus = ne...
SwitchingSwitchingSwitching
1 line of code
var primus = new Primus(server, { !
transformer: “sockjs" // engine.io, socket.io etc!
});
1 line of code
1 line of code
module.exports = require(“primus/transformer").extend({!
server: function () {!
// This is only exposed and...
StabilityStabilityStability
manual patching
manual patching
Stream CompatibleStream CompatibleStream Compatible
stream compatible
primus.on("end", function disconnected() {!
console.log("connection ended");!
});!
!
primus.end();!
prim...
EncodingEncodingEncoding
message encoding
var primus = new Primus(server, { !
parser: "JSON" // JSON by default!
});
message encoding
var primus = new Primus(server, { !
parser: "EJSON" // or binary-pack or a third party module!
});
message encoding
module.exports = {!
encoder: function (data, fn) {!
// encode data to a string.!
},!
!
decoder: function ...
message encoding
primus.transform('incoming', function (packet) {!
// This would transform all incoming messages to foo;!
...
ReconnectReconnectReconnect
reconnect
var primus = new Primus("http://localhost:8080", {!
strategy: "disconnect, online"!
});
BroadcastBroadcastBroadcast
broadcast
primus.write("message"); // send message to all users!
!
primus.forEach(function (spark) {!
// Or iterate over a...
Node clientNode clientNode client
node.js
var primus = new Primus(server)!
, Socket = primus.Socket;!
!
var client = new Socket(“http://localhost:8080”);!
!...
PluginsPluginsPlugins
plugins
// The long awaited Socket.IO 1.0 release with Primus:!
!
var server = require("http").createServer(fn)!
, primus ...
plugins
module.exports = {!
server: function () {!
// This is only exposed and ran on the server.!
},!
!
client: function ...
and middlewareand middlewareand middleware
PluginsPluginsPlugins
middleware
var server = require("http").createServer(fn)!
, primus = new Primus(server, { transformer:"sockjs" });!
!
prim...
!
3rdEden
"
3rd-Eden
fb
arnout.kazemier
That's it! Thanks & check it out on
http://primus.io
http://primus.io
Transforming WebSockets
Transforming WebSockets
Upcoming SlideShare
Loading in...5
×

Transforming WebSockets

3,757

Published on

An introduction to WebSockets and why Primus might be a better fit for your project. This presentation was given at WebRebels

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,757
On Slideshare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
22
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Transforming WebSockets"

  1. 1. TransformingTransformingTransforming WebSocketsWebSocketsWebSockets
  2. 2. ! 3rdEden " 3rd-Eden fb arnout.kazemier
  3. 3. the good partsthe good parts WebSocketsWebSockets the good parts WebSockets
  4. 4. Chrome 20 Firefox 12 Opera 12.1 Safari 6 Internet Explorer 10
  5. 5. Chrome 4 Firefox 4 Opera 11 Safari 4.2 Internet Explorer 10
  6. 6. oh, it’s bi-directional & supports binary oh, it’s bi-directional & supports binary oh, it’s bi-directional & supports binary
  7. 7. The EndThe EndThe End
  8. 8. that nobody told youthat nobody told youthat nobody told you The partsThe partsThe parts
  9. 9. HTTP proxy settings in your network settings can cause a full browser crash.
  10. 10. user agent sniff if (! // Target safari browsers! $.browser.safari! ! // Not chrome! && !$.browser.chrome! ! // And correct WebKit version! && parseFloat($.browser.version, 0) < 534.54! ) {! // Don’t use WebSockets! return;! }
  11. 11. Writing to a closed WebSocket can cause a full browser crash
  12. 12. write crash var ws = new WebSocket("wss://localhost:8080/");! ! ws.onmessage = function message(event) {! // Wrap sends in a setTimeout out to allow the! // readyState to be correctly set to closed. But! // Only have this delay on mobile devices! if (mobile) return setTimeout(function () {! ws.send("Sup Oslo");! }, 0);! ! ws.send("Sup Oslo");! };
  13. 13. Pressing ESC in Firefox closes the WebSocket connection
  14. 14. connection end $('body').keydown(function (e) {! // make sure that you capture the `esc` key and! // prevent it's default action from happening! if (e.which === 27) e.preventDefault();! });
  15. 15. Firefox can create ghost connections when you connect during ws.onclose.
  16. 16. Don’t use self signed SSL certificates, not for development and not in production
  17. 17. 4G, 3G, LTE, mobile providers WTF ARE YOU DOING?? — Reverse proxy
  18. 18. Virus scanners such as AVG block WebSockets.
  19. 19. User, network and server firewalls block WebSockets.
  20. 20. Load balancers don't understand and block WebSockets.
  21. 21. So yeah.. Real-Time is HARD
  22. 22. What if…What if…What if… we could change thiswe could change thiswe could change this
  23. 23. Frameworks!Frameworks!Frameworks!
  24. 24. framework ws https://github.com/einaros/ws/ super damned fast supports binary cross domain all the cool kids are doing it i’m the only somewhat maintainer no fallbacks or downgrading broken by firewalls/virus scanners only server, no client module*
  25. 25. framework socket.io http://github.com/learnboost/socket.io multiple transports cross domain invested with bugs poorly / not maintained / left for dead no message order guarantee dies behind firewall/virusscanners
  26. 26. framework engine.io http://github.com/learnboost/engine.io supports multiple transports cross domain upgrade instead of downgrade works behind firewalls & virusscanners not well battle tested yet no message order guarantee
  27. 27. framework browserchannel https://github.com/josephg/node-browserchannel multiple transports client maintained by google message order guaranteed works behind firewalls & virusscanners not cross domain no websocket support coffeescript on the server ._.
  28. 28. framework sockjs https://github.com/sockjs/sockjs-node/ multiple transports (tons of them) cross domain poor error handling no query string allowed for connect argh, more coffeescript connection delay with firewalls poorly maintained in the way of developers
  29. 29. They all have different use cases and API's. ! Changing product specs == rewrite
  30. 30. we could change this toowe could change this toowe could change this too What if…What if…What if…
  31. 31. npm install primus
  32. 32. Primus wraps and improves popular real-time frameworks. So you can focus on building apps.
  33. 33. CommunityCommunityCommunity
  34. 34. community
  35. 35. community
  36. 36. 1014 1 5 stars, but growing steady star it on http://github.com/primus/primus 1014 1 line of code to switch between excluding adding a framework to your package.json different frameworks build-in socket.io, engine.io, sockjs, websockets, browserchannel, but allows addition third party 5 1014 1 5
  37. 37. community
  38. 38. community
  39. 39. 50 31 50 31 50 different plugins substream, emit, primus-emitter, primus-cluster, primus-rooms, primus-multiplex, primus-redis different authors damonoehlman, mmalecki, jcrugzz, daffl, balupton, cayasso & many more 31
  40. 40. community #primus on irc.freenode.net questions are bugs, ask them in our github issue tracker
  41. 41. why was primus inventedwhy was primus inventedwhy was primus invented HistoryHistoryHistory
  42. 42. history real-time layer for the bigpipe app framework
  43. 43. history which had an engine.io wrapper
  44. 44. history no single point of failure
  45. 45. history extracted and released as ! primus
  46. 46. Use casesUse casesUse cases
  47. 47. use cases module & framework authors
  48. 48. use cases startups & web developers
  49. 49. Learning Primus Learning Primus Learning Primus
  50. 50. learning primus cd your-awesome-project! ! $ npm install --save primus ws! ! echo "??" ! echo “profit!”! ! vim index.js
  51. 51. learning primus 'use strict';! ! var Primus = require("primus")! , server = require("http").createServer(fn)! , primus = new Primus(server, { transformer:"ws" });! ! primus.on("connection", function connection(spark) {! console.log("connection received", spark.id);! spark.write("ohai");! ! spark.on("data", function data(msg) {! console.log("received", msg);! });! });! ! server.listen(8080);
  52. 52. learning primus <script src="http://localhost:8080/primus/primus.js"></script>! <script>! 'use strict';! ! var primus = new Primus("http://localhost:8080");! ! primus.on("open", function connected() {! console.log("connection opened");! primus.write("ohai");! });! ! primus.on("data", function data(msg) {! console.log(“received", msg);! });! </script>
  53. 53. SwitchingSwitchingSwitching
  54. 54. 1 line of code var primus = new Primus(server, { ! transformer: “sockjs" // engine.io, socket.io etc! });
  55. 55. 1 line of code
  56. 56. 1 line of code module.exports = require(“primus/transformer").extend({! server: function () {! // This is only exposed and ran on the server.! },! ! client: function () {! // This is stringified end send/stored in the client.! // Can be ran on the server, if used through Node.js! },! ! // Optional library for the front-end, assumes globals! library: fs.readFileSync(__dirname +"./yourclientlib.js")! });
  57. 57. StabilityStabilityStability
  58. 58. manual patching
  59. 59. manual patching
  60. 60. Stream CompatibleStream CompatibleStream Compatible
  61. 61. stream compatible primus.on("end", function disconnected() {! console.log("connection ended");! });! ! primus.end();! primus.write();! ! fs.createReadStream(__dirname + '/index.html').pipe(spark, {! end: false! });
  62. 62. EncodingEncodingEncoding
  63. 63. message encoding var primus = new Primus(server, { ! parser: "JSON" // JSON by default! });
  64. 64. message encoding var primus = new Primus(server, { ! parser: "EJSON" // or binary-pack or a third party module! });
  65. 65. message encoding module.exports = {! encoder: function (data, fn) {! // encode data to a string.! },! ! decoder: function (data, fn) {! // decode data to an object! },! ! // Optional library for the front-end, assumes globals! library: fs.readFileSync(__dirname +"./yourclientlib.js")! };
  66. 66. message encoding primus.transform('incoming', function (packet) {! // This would transform all incoming messages to foo;! packet.data = 'foo';! });! ! primus.transform('outgoing', function (packet) {! // This would transform all outgoing messages to foo;! packet.data = 'foo';! }); transforming
  67. 67. ReconnectReconnectReconnect
  68. 68. reconnect var primus = new Primus("http://localhost:8080", {! strategy: "disconnect, online"! });
  69. 69. BroadcastBroadcastBroadcast
  70. 70. broadcast primus.write("message"); // send message to all users! ! primus.forEach(function (spark) {! // Or iterate over all connections, select the once you! // want and only write to those! ! spark.write("message");! });
  71. 71. Node clientNode clientNode client
  72. 72. node.js var primus = new Primus(server)! , Socket = primus.Socket;! ! var client = new Socket(“http://localhost:8080”);! ! // or if you want to connect to a remote server:! var primus = require(“primus”).createSocket({/* options */});
  73. 73. PluginsPluginsPlugins
  74. 74. plugins // The long awaited Socket.IO 1.0 release with Primus:! ! var server = require("http").createServer(fn)! , primus = new Primus(server, { transformer:"engine.io" });! ! primus.use(“emitter","primus-emitter")! .use(“multiplex”, require(“primus-multiplex”))! .use(“primus-emitter”, "primus-rooms");
  75. 75. plugins module.exports = {! server: function () {! // This is only exposed and ran on the server.! },! ! client: function () {! // This is stringified end send/stored in the client.! // Can be ran on the server, if used through Node.js! },! ! // Optional library for the front-end, assumes globals! library: fs.readFileSync(__dirname +"./yourclientlib.js")! };
  76. 76. and middlewareand middlewareand middleware PluginsPluginsPlugins
  77. 77. middleware var server = require("http").createServer(fn)! , primus = new Primus(server, { transformer:"sockjs" });! ! primus.before(“session”, require(“session-parse-module”))! .before(“middleware-name”, "middleware-module-name");
  78. 78. ! 3rdEden " 3rd-Eden fb arnout.kazemier That's it! Thanks & check it out on http://primus.io
  79. 79. http://primus.io
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×