วันที่ 3 มาเริ่มลุย Node.js+socket.io ในรูปแบบการใช้งานอื่นๆดูบ้างนะครับ
ครั้งลองดึง .html ขึ้นมาแสดงคำว่า Hello World โดยเขียน
app.js แล้วก็เรียกด้วยคำสั่งของ Node app.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
Untitled Document
Hello world
ไม่มีความคิดเห็น:
แสดงความคิดเห็น