socket.io基本介紹

## 創建一個nodejs項目 步驟1:創建項目目錄 
步驟2:初始化nodejs項目
命令:npm init -f

結果如下:

## 在nodejs項目安裝socket.io模塊 命令:npm install sokcet.io 
socket.io網站:https://socket.io/
## socket.io快速入門案例 客戶端:index.html ```
服務端:server.js [node.js]
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8888);
//URL請求處理
/*
服務器web請求處理器
作用: 當客戶端請localhost:8888時,打開默認頁面 /index.html
*/
function handler (req, res) {
//打開默認頁面
fs.readFile(__dirname + '/index.html',
//響應處理方法
function (err, data) {
//情況1:如果 err 不為空,那么表示沒有找到 /index.html
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
//情況2:找到了 /index.html
res.writeHead(200);
res.end(data);
});
}
// socket請求處理
io.on('connection', function (socket) {
// 向客戶端的自定義事件'news'發送數據
socket.emit('news', { hello: 'world' });
// 創建自定義事件 my other event
socket.on('my other event', function (data) {
console.log(data);
});
});
