nodejs+expressjs+ws實現了websocket即時通信,服務器和客戶端互相通訊

nodejs代碼html

// 導入WebSocket模塊:
const WebSocket = require('ws');

// 引用Server類:
const WebSocketServer = WebSocket.Server;

// 實例化:
const wss = new WebSocketServer({
  port: 3001
});
wss.on('connection', function (ws) {
  console.log(`ws 已經鏈接上`);
  ws.on('message', function (message) {

    console.log(`收到客戶端的數據: ${message}`);
    ws.send(`服務端接收到數據,給客戶端返回數據: ${message}`, (err) => {
      if (err) {
        console.log(`[SERVER] error: ${err}`);
      }
    });
  })
});
2. html代碼
      // 打開一個WebSocket:
      var ws = new WebSocket('ws://localhost:3001');
     
      // 響應onmessage事件:
      ws.onmessage = function (msg) { console.log(msg); };
     
      // 給服務器發送一個字符串:
      ws.addEventListener('open', function () {
        let msg = '我是客戶端: ' + location.href
          ws.send(msg)
      });
3. 固然  必須提早導入ws模塊  npm i ws
相關文章
相關標籤/搜索