Permalink
Browse files

partly working initial example

  • Loading branch information...
0 parents commit 366e82414527d581dd818cc4def36582a8f65a35 @substack committed Sep 9, 2012
Showing with 75 additions and 0 deletions.
  1. +11 −0 example/repl.js
  2. +28 −0 index.js
  3. +36 −0 readme.markdown
@@ -0,0 +1,11 @@
+var http = require('../');
+var repl = require('repl');
+
+var server = http.createServer(function (req, res) {
+ if (req.headers.upgrade) {
+ res.write('# repl party server\n');
+ repl.start({ input : req, output : res });
+ }
+ else res.end('beep boop');
+});
+server.listen(8000);
@@ -0,0 +1,28 @@
+var http = require('http');
+
+Object.keys(http).forEach(function (key) {
+ exports[key] = http[key];
+});
+
+exports.createServer = function (cb) {
+ var server = http.createServer(cb);
+
+ server.on('upgrade', function (req, socket, head) {
+ var res = new http.ServerResponse(req);
+ res.assignSocket(socket);
+ res.on('finish', function () {
+ res.detachSocket(socket);
+ socket.destroySoon();
+ });
+ res.useChunkedEncodingByDefault = false;
+
+ socket.on('data', function (buf) {
+ req.emit('data', buf);
+ });
+ server.emit('request', req, res);
+
+ if (head.length) req.emit('data', head);
+ });
+
+ return server;
+};
@@ -0,0 +1,36 @@
+# http-noupgrade
+
+merge `'upgrade'` requests back into the `'request'` listener
+
+# example
+
+``` js
+var http = require('http-noupgrade');
+
+var server = http.createServer(function (req, res) {
+ if (req.headers.upgrade) {
+ repl.start({ input : req, output : res });
+ }
+ else res.end('beep boop');
+});
+server.listen(8000);
+```
+
+# hypothesis
+
+Emitting an `'upgrade'` event with `(request, socket, head)` parameters makes
+using and writing websocket server handlers much more complicated than it needs
+to be. Because the necessary events are spread out across both `'upgrade'` and
+`'request'`, websocket libraries tend to have an `install()` mechanism for
+adding the listeners themselves. This is unfortunate because it obscures the
+correspondence between the original http request and the resulting duplex
+stream. Instead of just passing a `(req,res)` explicitly to a handler after
+performing session checks, the websocket or fallback abstraction takes control
+of the http server by punching methods, events, and otherwise being hacky and
+brittle.
+
+Since http request and response objects can already be paired to make a full
+duplex connection, have well-understood and expected semantics, and more
+adequately describe the actual http protocol in the case of an upgrade, we
+should just let the `'request'` listener handle `'upgrade'` events instead of
+using a separate event.

0 comments on commit 366e824

Please sign in to comment.