仙台の山奥で自転車に乗ったり転んだり

愛車の GIOS でサイクリングしたりポタリングしたり、それをブログに記録してみたり。ロードバイクや自転車や坂のことを書いてみたり。ときたまプログラムのことを忘れないようにメモってみたり。

Javascriptを勉強中、node.js

var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

コピペしてきたHelloWorld

↑だけではつまらないので、なんちゃってアクセス数を制限サーバ

var PORT_NUMBER    = 8124;
var INTERVAL       = 5000;
var MAX_CONNECTION = 5;

function Connection() {
    this.stack = [];
};
Connection.prototype.push = function(value) {
    return this.stack.push(value);
};
Connection.prototype.remove = function(pid) {
    for (var i = 0, l = this.stack.length; i < l; i++) {
        var value = this.stack.shift();
        if (value !== pid) {
            this.stack.push(value);
        };
    };
};
Connection.prototype.isPermissible = function(pid) {
    return (this.stack.length < MAX_CONNECTION);
};

var processId   = 1000000;
var connections = new Connection();

var http = require('http');
http.createServer(function (request, response) {
    ++processId;

    var body;
    if (connections.isPermissible()) {
        body = 'Hello World\n';
        (function(pid) {
            connections.push(pid);
            setTimeout(function openConnection() {
                connections.remove(pid);
            }, INTERVAL);
        }) (processId);
    } else {
        body = 'Busy\n';
    };

    var responseHeaders = {
        'Content-Type': 'text/plain'
    };
    response.writeHead(200, responseHeaders);
    response.end(body);
}).listen(PORT_NUMBER);

console.log('Server running at http://127.0.0.1:%s/', PORT_NUMBER);

非同期で応答

var PORT_NUMBER = 8124;
var INTERVAL    = 500;

function Body(text) {
    this.text  = text;
    this.index = 0;
}
Body.prototype.character = function() {
    if (!this.exists()) {
        return false;
    }
    var c = this.text.charAt(this.index);
    ++this.index;

    return c;
};
Body.prototype.current = function() {
    return this.index;
};
Body.prototype.length = function () {
    return this.text.length;
};
Body.prototype.exists = function() {
    var index  = this.current();
    var length = this.length();

    return (index < length);
};

var http = require('http');
http.createServer(function (request, response) {
    var responseHeaders = {
        'Content-Type': 'text/plain'
    };
    response.writeHead(200, responseHeaders);
    response.write('Start\n');

    var body = new Body('Hello World');
    setInterval(function outputResponse() {
        var character = body.character();
        if (character === false) {
            clearInterval(this);
            setTimeout(function closeResponse() {
                response.end('END\n');
            }, INTERVAL);

            return;
        };

        response.write(character + '\n');
        console.log('Char=%s', character);
    }, INTERVAL);
}).listen(PORT_NUMBER);

console.log('Server running at http://127.0.0.1:%s/', PORT_NUMBER);

これだけだと寂しいので、チャット風アプリのWebAPI

var PORT_NUMBER = 8124;

var messages = [];

var http = require('http');
var queryString = require('querystring');
var util = require('util');

http.createServer(function (request, response) {
    if (request.method === 'POST') {
        var body = '';
        request.on('data', function(data) {
            body += data;
        });
        request.on('end',function() {
            var POST = queryString.parse(body);
            messages.push(POST.message);
            response.writeHead(200, {
                'Content-Type': 'text/plain',
                'Access-Control-Allow-Origin': '*'
            });
            response.end('OK\n');
        });
    } else if (request.method === 'GET') {
        response.writeHead(200, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        });
        var data = util.format('%j\n', messages);
        response.end(data);
    };
}).listen(PORT_NUMBER);

console.log('Server running at http://127.0.0.1:%s/', PORT_NUMBER);