文、意如
認識 Socket.IO
Socket.IO 是一個即時網頁 web 應用的 JavaScript 庫。
可使伺服器與客戶端間即時雙向溝通。
安裝環境
先安裝 node.js 、npm、pm2

建立一個資料夾
建立:mkdir 資料夾名稱
進入:cd 資料夾名稱
基礎安裝初始化:npm init

目錄參考如下:

安裝:socket.io
npm install --save express socket.io

新增app.js檔案
var app = require('express')();
var http = require('http').Server(app);
app.get('/',function(req,res){
    res.sendfile('index.html');
});
 
http.listen(3000,function(){
    console.log('listening on *:3000');
});
新建index.html
<html>
    <head><title>MyTestSoketio</title></head>
    <body>
        Hi,Socketio
    </body>
</html>
啟動
pm2 start app.js --watch
note: 加上--watch (只要有修改任何,馬上自動更新

到瀏覽器輸入 http://localhost:3000/

app.js
var io = require('socket.io')(http);
//每當有人連線就會執行
io.on('connection',function(socket){
    console.log("一個使用者連線");
 
    //每當有人離線就會執行
    socket.on('disconnect',function(){
        console.log("有一個使用者離線了");
    });
});
index.html
<html>
    <head><title>MyTestSoketio</title></head>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io("localhost:3000");
    </script>
    <body>
        Hi,Socketio
    </body>
</html>

把log開起來
pm2 log

打開網頁
到瀏覽器輸入 http://localhost:3000/

查看log

關閉 http://localhost:3000/ 頁面

參考: https://www.tutorialspoint.com/socket.io/socket.io_hello_world.htm
Yiru@Studio - 關於我 - 意如