使用 socket.io.js 實現 websocket 實時通訊

背景


最近公司在做一個快遞櫃項目,需要與快遞櫃設備端進行實時通訊,因此接觸了 websocket.

websocket 作用


簡單的說: 傳統 http 通訊一次交互數據後就斷開連接了,服務端沒法主動向客戶端推送信息。 而長連接的 websocket 解決了這一問題

下面會有一個簡單的例子介紹 socket.io.js 的使用

github 代碼地址

將上述代碼下載至本地,執行下列操作

npm install express --save
npm install socket.io --save
node server.js

打開在瀏覽器打開 localhost , 如下效果

localhost

通訊

源碼分析

客戶端代碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    input {
      background-color: #fff;
      background-image: none;
      border-radius: 4px;
      border: 1px solid #bfcbd9;
      box-sizing: border-box;
      color: #1f2d3d;
      font-size: inherit;
      height: 40px;
      line-height: 1;
      outline: 0;
      padding: 3px 10px;
    }
    .el-button--primary {
      color: #fff;
      background-color: #20a0ff;
      border-color: #20a0ff;
    }
    .el-button {
      display: inline-block;
      line-height: 1;
      white-space: nowrap;
      cursor: pointer;
      background: #00aac5;
      border: 1px solid #c4c4c4;
      color: #fff;
      margin: 0;
      padding: 10px 15px;
      border-radius: 4px;
      outline: 0;
      text-align: center;
    }
  </style>
</head>
<body>
  <div>
    <div id="content">
    </div>
  </div>
  <div>
    <input type="text" id="input">
    <button class="el-button el-button--primary el-button--large" type="button" onclick="say()"><span>發送消息</span></button>
  </div>
  <script src="./socket.io.js"></script>
  <script>
    // 建立連接
    var socket = io.connect('http://localhost:80');
    // 監聽 message 會話
    socket.on('message', function (data) {
      let html = document.createElement('p')
      html.innerHTML = `系統消息:<span>${data.hello}</span>`
      document.getElementById('content').appendChild(html)
      console.log(data);
    });
    // 按鈕點擊事件
    function say() {
      let t = document.getElementById('input').value
      if (!t) return
      let html = document.createElement('p')
      html.innerHTML = `你細聲說:<span>${t}</span>`
      document.getElementById('content').appendChild(html)
      socket.emit('say', { my: t});
    }
    // 監聽 news 會話
    socket.on('news', function (data) {
      console.log(data);
      let html = document.createElement('p')
      html.innerHTML = `小皮咖說:<span>我知道了,你說“${data.hello}”</span>`
      document.getElementById('content').appendChild(html)
    });
    // 監聽吃飯會話
    socket.on('eating', function (data) {
      console.log(data);
      let html = document.createElement('p')
      html.innerHTML = `小皮咖說:${data.hello}`
      document.getElementById('content').appendChild(html)
    });
  </script>
</body>
</html>

服務端代碼

// 使用 express 框架
var app = require('express')();
var express = require("express");
var server = require('http').Server(app);
// 引入 socket.io
var io = require('socket.io')(server);
// 監聽 80 端口
server.listen(80);
// 開啓靜態資源服務
app.use(express.static("./static"));
// io 各種事件
io.on('connection', function (socket) {
  console.log('websocket has connected')
  socket.emit('message', { hello: '歡迎鏈接' });
  socket.on('my other event', function (data) {
    console.log(data);
    socket.emit('message', { hello: '發送成功' });
  });
  socket.on('say', function (data) {
    console.log(data);
    if (data.my === '走,一起吃飯吧') {
      io.sockets.emit('eating', { hello: '果斷走起呀!' });
      return
    }
    io.sockets.emit('news', { hello: data.my });
  });
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章