Weitere ähnliche Inhalte
Ähnlich wie Node.jsでサーバプログラマ デビューしよう (20)
Mehr von Yuusuke Takeuchi (20)
Node.jsでサーバプログラマ デビューしよう
- 9. コードの説明 WEBサーバ
• これだけで、Webサーバが書けます
var app = require(‘http’).createServer(handler) //サーバのテンプレート読み込み
app.listen(80); //80番ポートでサーバを起動
function handler (req, res) { //リクエストがある場合に呼び出される関数を定義
fs.readFile(__dirname + '/index.html', //index.htmlをロード
function (err, data) { //ファイルロードに失敗時エラー処理
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
!
res.writeHead(200); //ヘッダにHTTP200(成功)を指定
res.end(data); //index.htmlをクライアントに送信
});
}
- 10. コードの説明 サーバ側
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' }); //クライアントにメッセージ送信
socket.on('my other event', function (data) { //クライアントからメッセージ受信
console.log(data); //受信した時の処理
});
});
var socket = io.connect('http://localhost');
socket.on('news', function (data) { //サーバからメッセージ受信
console.log(data); //メッッセージ受信の処理
socket.emit('my other event', { my: 'data' }); //サーバへメッセージ送信
});
• 送信、受信も1行で書けます
サーバ
クライアント