Created
November 1, 2016 08:47
-
-
Save nibral/d4a3cb314eddeb1ab0567812c37ae532 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 参考: | |
// http://www.misuzilla.org/Blog/2016/01/31/CreateYourOwnHttpServerUsingCSharp | |
// http://qiita.com/akiray03/items/3607c60ec8b221b3c2ba (Node.jsはブロックしないよ!) | |
'use strict'; | |
const net = require('net'); | |
const HTTP_RESPONSE = [ | |
"HTTP/1.0 200 OK", | |
"Content-Type: text/plain; charset=UTF-8", | |
"", | |
"this is the2 server." | |
]; | |
const server = net.createServer(socket => { | |
console.log('client connected:'); | |
// 受信した行をコンソールに出力 | |
// 空行が来たらレスポンスを返す | |
const parse = line => { | |
if (line.length === 0) { | |
HTTP_RESPONSE.forEach(responseLine => { | |
socket.write(`${responseLine}\r\n`); | |
console.log(`< ${responseLine}`); | |
}); | |
socket.end(); | |
} else { | |
console.log(`> ${line}`); | |
} | |
}; | |
// データ到着 | |
let fragment = ''; | |
socket.on('data', buffer => { | |
const chunk = buffer.toString(); | |
if (chunk === '') { | |
return; | |
} | |
// 一つ前の処理で処理されなかった文章の断片 | |
const lines = chunk.split('\r\n'); | |
lines[0] = fragment + lines[0]; | |
// 最後の改行より後の文字は次の処理に回す | |
fragment = lines.pop(); | |
// 各行をコールバックに渡す | |
lines.forEach(function (line) { | |
parse(line); | |
}); | |
}); | |
// socketを閉じる | |
socket.on('end', () => { | |
if (fragment.length > 0) { | |
parse(fragment); | |
} | |
console.log('client disconnected'); | |
}); | |
}); | |
server.on('error', error => { | |
console.error(error); | |
}); | |
server.listen(process.env.PORT || 3000, () => { | |
const address = server.address(); | |
console.log('listening on port %d', address.port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment