Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created May 4, 2012 10:25
Show Gist options
  • Save ishiduca/2593889 to your computer and use it in GitHub Desktop.
Save ishiduca/2593889 to your computer and use it in GitHub Desktop.
テスト用のwebsocketserver
// server.js * this file
// /public/
// index.html
// /js/
// fuga.js
// hoge.js
// /css/
// /img/
// /etc/
var WSS = require('ws').Server
, http = require('http')
, url = require('url')
, fs = require('fs')
, mime = require('mime')
, port = 3210
, faviPath = '/favicon.ico'
, router = { staticPath : __dirname + '/public'
, useStatic : ('/js/ /css/ /img/ /etc/').split(' ')
, INDEX_HTML : __dirname + '/public/index.html'
, routes : {}
}
;
router.route = function (pathname) {
if (typeof this.routes[pathname] !== 'undefined')
return this.routes[pathname];
if ((! pathname) || pathname === '/') {
this.routes[pathname] = this.INDEX_HTML;
return this.INDEX_HTML;
}
for (var i = 0, len = this.useStatic.length; i < len; i+=1) {
if (pathname.indexOf(this.useStatic[i]) > -1) {
this.routes[pathname] = this.staticPath + pathname;
return this.staticPath + pathname;
}
}
this.routes[pathname] = pathname;
return pathname;
};
function log () {console.log(Array.prototype.join.apply(arguments, [' ']));}
function Response (res, req, method) {
this.request = req;
this.response = res;
this.method = method;
}
Response.prototype.res = function (statusCode, content_type, data) {
var res = this.response;
res.writeHead(statusCode, { 'Content-Type' : content_type });
res.end(data);
};
Response.prototype.send = function (pathname) {
var that = this
, _pathname = router.route(pathname)
, content_type = mime.lookup(_pathname)
, encoding = (/(image|video|audio)/.test(content_type))
? undefined : 'utf-8'
;
fs.readFile(_pathname, encoding, function (err, data) {
if (err) {
that.res( 500
, 'application/javascript'
, JSON.stringify({ error : err.toString() })
);
log(that.method, 500, err);
return;
}
that.res(200, content_type, data);
log(that.method, 200, pathname, '->', _pathname, data.length);
});
};
var server, wss;
server = http.createServer(function (request, response) {
var method = request.method.toUpperCase()
, pathname = url.parse(request.url).pathname
, res = new Response(response, request, method)
;
if (pathname === faviPath) return res.res(method, 200, 'image/x-icon');
res.send(pathname);
});
wss = new WSS({ server : server, path : null});
wss.sockets = [];
wss.broadcast = function (message, flags) {
if (typeof message === 'undefined') return;
wss.sockets.forEach(function (ws) { ws.send(message, flags); });
};
wss.on('connection', function (ws) {
wss.sockets.push(ws);
log('webSocketServer "connected" - length:', wss.sockets.length);
ws.on('close', function () {
wss.sockets = wss.sockets.filter(function (_ws) {
return (ws === _ws) ? false : true;
});
log('webSocketServer "disconnected" - length:', wss.sockets.length);
});
ws.on('message', function (message, flags) {
wss.broadcast(message, flags);
log('webSocketServer "broadcasting" - length:', wss.sockets.length);
});
});
server.listen(port);
log('serser start to listen on port', port);
@ishiduca
Copy link
Author

ishiduca commented May 4, 2012

function createWebSocket (binmode) {
    var uri      = document.location.href
      , reg      = /^(http|https)(.*)(\/?)$/
      , parseUri = uri.match(reg)
      , ws       = new WebSocket('ws' + parseUri[2])
    ;
    ws.onopen = function () {
        if (binmode) ws.binaryType = 'arraybuffer';
        log('open websocket - binaryType:', ws.binaryType);
    };
    ws.onclose = function (code, message) {
        log('close websocket');
    };
    return ws;
}
function log () {
    console.log(Array.prototype.join.apply(arguments, [ ' ' ]));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment