nodejs + express實現websocket即時通訊的最簡應用

現在很多項目都需要內嵌一個簡單的即時通訊模塊,做用戶之間的快速溝通,我們昨天也實現了一個,用的socket.io這個插件,可以去npm網站下載或直接npm安裝。

現在把最簡配置貼出來,以備參考:

首先是服務端的route.js

const express = require('express')

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

const io = require('socket.io')(server)
//在線用戶
var onlineUsers = {};
//當前在線人數
var onlineCount = 0;
io.on('connection', function (conn) {
  conn.on('login', function (obj) {
    console.log('login', obj);
    if (!onlineUsers.hasOwnProperty(obj.userid)) {
      onlineUsers[obj.userid] = {
        id: obj.userid,
        conn: conn
      };
      onlineCount++;
    }
  });
  conn.on('disconnect', function () {
    if (onlineUsers.hasOwnProperty(conn.userid)) {
      var obj = {
        id: obj.userid,
        conn: conn
      };
      delete onlineUsers[conn.userid];
      onlineCount--;
    }
  });
  conn.on('sendMsg', function (data) {    
    var rids = data.to.split(',')
    for (let id of rids) {
      if (id) {
        var receiver = onlineUsers[id]
        if (receiver) {
          receiver.conn.emit('receiveMsg', data.msg)
        }
      }
    }
  })
});

server.listen('3000', () => {
  console.log('open Browser on http://127.0.0.1:3000')
})

然後是網站前端的頁面調用,這裏注意也要使用socket.io的客戶端js插件,建議下載下來:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="/public/socket.io.js"></script>
  <title>Document</title>
</head>

<body>
  <div>
    <div>
      <div>
        <h1>WebSocket chat,歡迎使用:</h1>
      </div>
      <div>
        <label>輸入用戶名:</label>
        <input type="text" id="name" />
        <button id="conn">連接</button>
        <label>輸入聊天對象用戶名:</label>
        <input type="text" id="talkname" />
      </div>
      <div>
        <div id="messages"></div>
      </div>
      <hr>
      <div>
        <input type="text" id="msg" />
        <button id="send">發送</button>
      </div>
    </div>
  </div>
  <script>
    var user = document.getElementById("name");
    var talk = document.getElementById("talkname");
    var btnConn = document.getElementById("conn");
    var msgs = document.getElementById("messages");
    var btnSend = document.getElementById("send");
    var txtMsg = document.getElementById("msg");
    var pattern = /^[\u4e00-\u9fa5]{2,10}$/;
    btnConn.onclick = function () {
      // if (!pattern.test(input.value)) {
      //   alert("名稱不能爲空且必須爲中文");
      //   return;
      // }
      var ws = io('ws://localhost:9001');
      ws.on('receiveMsg', function (data) {
        msgs.innerHTML += new Date().toUTCString() + ":" + data + "<br>";
      })

      ws.on('connect', function (e) {
        console.log("連接服務器成功");
        ws.emit('login',{userid: user.value});
      })
      send.onclick = function (e) {
        var txt = txtMsg.value;
        txtMsg.value = '';
        ws.emit('sendMsg',{from: user.value, to: talk.value, msg: txt});
      }
      document.onkeydown = function (e) {
        e = e || window.event;
        if (e.keyCode == 13) {
          send.onclick();
          return false;
        }
      }
    }
  </script>
</body>

</html>

整個過程非常簡單,跟微軟提供的SignalR實現過程非常相似

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章