Skip to content

Instantly share code, notes, and snippets.

@shamabe
Forked from shigeki/hello.js
Created November 22, 2012 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamabe/4131753 to your computer and use it in GitHub Desktop.
Save shamabe/4131753 to your computer and use it in GitHub Desktop.
第1回Node.js入門勉強会 レポート課題
var http = require('http');
server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
server.close();
});
server.listen(8080, 0, function () {
console.log('Server running at http://localhost:8080/');
});

第1回の勉強会で重要だった点の一つは server.close() の挙動でした。 今回は、この server.close() の挙動についての課題です。

課題

A君は、ブラウザで1回閲覧したら HelloWorld のWebサーバが終了するプログラムを作ろうと hello.js を作りました。 だけど Chrome でアクセスすると下のようなエラーになってしまい、プログラムが正常に終了しません。

課題1

なぜエラーが発生したのかその理由を記述しなさい。

課題2

このプログラムを修正してエラーが発生せずA君がやりたかったプログラムを作りなさい。

提出方法

gist か ブログかに記載して、URLをメーリングリストに連絡してください。

##提出期限

次回勉強会開催まで。(その前に出そろえば答え合わせでもしましょうか)

> node hello.js
Server running at http://localhost:8080/

net.js:1046
    throw new Error('Not running');
          ^
Error: Not running
    at Server.close (net.js:1046:11)
    at Server.<anonymous> (/home/ohtsu/hello.js:5:10)
    at Server.EventEmitter.emit (events.js:99:17)
    at HTTPParser.parser.onIncoming (http.js:1807:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
    at Socket.socket.ondata (http.js:1704:22)
    at TCP.onread (net.js:403:27)

回答1

Chromeがコンテンツの取得と同時にfaviconを取得しようとし、requestイベントのコールバックが2回呼ばれている。 これによりserver.close()が2回呼ばれた時点でエラーを吐いている。

回答2

server.closeは新規接続を受け付けないようにするメソッド。 まずconnectionイベント時にserver.close()を実行することで、 以降の接続は受け付けず、server.closeは正確に1度だけ実行される。

server.on('connection', function() {
    server.close();
});

ただしKeep-Aliveでつないでいるため、これだけでは接続がタイムアウトするまでサーバが閉じてくれない。

接続を明示的に切るには、レスポンス完了後のendイベントでreq.connection.destroy()を実行する。

var server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
    req.once('end', function() {
        req.connection.destroy();
    });
});

もしくはres.shouldKeepAlive = falseでKeep-Alive自体を無効にする。

var server = http.createServer(function(req, res) {
    res.shouldKeepAlive = false;
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment