socket.io入門

關於Socket.Io

  • Socket.IO是一個庫,它支持瀏覽器和服務器之間的實時、雙向和基於事件的通信。
  • Socket.IO是不WebSocket實現。儘管Socket.IO確實在可能的情況下使用WebSocket作爲傳輸,但它在每個數據包中添加了一些元數據:數據包類型、名稱空間和當需要消息確認時的ack id。這就是爲什麼WebSocket客戶端無法成功連接到Socket.IO服務器,Socket.IO客戶端也無法連接到WebSocket服務器。(WebSocket的原理就是利用Http請求產生握手,握手之後,二者轉用TCP協議進行交流,但是如果使用WebSocket,需要瀏覽器和服務器都支持纔可以,例如IE9以下瀏覽器不支持HTML5,則不行)
  • 文檔

Demo

package.json

{
  "name": "study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "express": "^4.16.3",
    "socket.io": "^2.0.4"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

index.js

const express = require('express')
const app = express()

const server = require('http').Server(app)

const io = require('socket.io')(server)

app.get('/', (req,res)=>{
    res.sendFile(__dirname + '/index.html')
})

app.get('/one', (req,res)=>{
    res.sendFile(__dirname + '/one.html')
})

app.get('/two', (req,res)=>{
    res.sendFile(__dirname + '/two.html')
})

// 監聽用戶是否進入,不管多少個用戶都是一個connection
io.on('connection', socket=>{
    console.log('有客人來了')

    // socket 監聽客戶端發送的數據msg
    socket.on('chatroom', msg=>{ // 接收chatroom命令,這裏的msg就是用戶輸入的內容
        io.emit('chatroom_1', `服務器說:${msg}`) // 發出chatroom_1命令,回覆客戶端消息
    })

    socket.on('chatone', msg=>{
        io.emit('chatone', `one: ${msg}`)
    })

    socket.on("chattwo",function(msg){
        io.emit("chattwo", `${msg.id}: ${msg.mes}`)
    });
})

server.listen(80)

index.html

<!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
        form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
    <input id="msg" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    var socket = io();
    $("form").submit(function(){
        socket.emit("chatroom", $("#msg").val()); // 發出chatroom命令,將用戶輸入的消息發送到服務器,即服務端的msg
        $("#msg").val(""); // 將input窗口的內容清空
        return false;
    });
    socket.on("chatroom_1",function(msg){ // 接收chatroom_1命令,這裏的msg是服務器返回的內容
        $("#messages").append("<li>" + msg + "</li>");
    });
</script>
</body>
</html>

one.html

<!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
        form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
    <input id="msg" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<!-- http://localhost:3000/socket.io/socket.io.js -->
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    var socket = io();
    $("form").submit(function(){
        socket.emit("chatone",$("#msg").val());
        $("#msg").val("");
        return false;
    });
    socket.on("chatone",function(msg){
        $("#messages").append("<li>" + msg + "</li>");
    });
</script>
</body>
</html>

two.html

<!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
        form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
    <input id="msg" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    var socket = io();
    $("form").submit(function(){
        socket.emit("chattwo",{mes:$("#msg").val(), id: Math.random()*Date.now()}); // 傳送json到服務器
        $("#msg").val("");
        return false;
    });
    socket.on("chattwo",function(msg){ // 這裏的msg是服務器返回的內容,即`${msg.id}: ${msg.mes}`(msg是服務器接收到的json)
        $("#messages").append("<li>"+msg+"</li>");
    });
</script>
</body>
</html>
  • socket.emit('action');表示發送了一個action命令,命令是字符串格式,在另一端接收時寫爲:socket.on('action',function(){...});
  • socket.emit('action',data);表示發送了一個action命令,還有data數據,在另一端接收時寫爲:socket.on('action',function(data){...});
  • socket.emit(action,arg1,arg2);表示發送了一個action命令,還有兩個數據,在另一端接收時寫爲:socket.on('action',function(arg1,arg2){...});
  • 在emit方法中包含回調函數,例如:socket.emit('action',data,function(arg1,arg2){});那麼這裏面有一個回調函數可以在另一端調用,另一端可以這麼寫:socket.on('action',function(data,fn){fn('a','b')});
  • 上面的data數據可以有0個或者多個,相應的在另一端改變function中參數的個數即可,function中的參數個數和順序應該和發送時一致,當然向fn這樣的回調函數也可以理解爲參數,一次發送不應該寫多個回調,否則只有最後一個起效,回調應作爲最後一個參數。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章