使用Node搭建一個本地的WebSocket服務

首先創建一個目錄,cd到目錄下, npm init -y 一路回車, 安裝一個插件 npm i websocket
建一個server.js文件

const WebSocketServer = require('websocket').server
const http = require('http')
const port = 8000
let time = 0

// 創建服務器
const server = http.createServer();
server.listen(port, () => {
  console.log(`${new Date().toLocaleDateString()} Server is listening on port ${port}`)
})


// websocket 服務器
const wsServer = new WebSocketServer({
  httpServer: server
})


// 建立連接
wsServer.on('request', (request) => {
  // 當前的連接
  console.log(request.origin, '=======request.origin=======')
  const connection = request.accept(null, request.origin)
  console.log(`${new Date().toLocaleDateString()} 已經建立連接`)

  //心跳💓 就30s一個吧
  // setInterval(() => {
  //   const obj = {
  //     value: '心跳💓' + time++
  //   }
  //   connection.send(JSON.stringify(obj))
  // }, 30000)

  // 監聽客戶端發來的的消息
  connection.on('message', (message) => {

    if (message.type === 'utf8') {//文本消息
      console.log('Received Message: ' + message.utf8Data);
      // connection.sendUTF(message.utf8Data);

    } else if (message.type === 'binary') {
      // binary 二進制流數據
      console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
      // connection.sendBytes(message.binaryData);
      
    }

  //轉發到其他客戶端
      wsServer.connections.forEach(function (client) {
        if (client !== connection) {
          client.send(message.binaryData);
        }
      });

  });

  // 監聽當前連接 當斷開鏈接(網頁關閉) 觸發
  connection.on('close', (reasonCdoe, description) => {
    console.log(`${new Date().toLocaleDateString()} ${connection.remoteAddress} 斷開鏈接`)
  })
})

僅此而已,一個WebSocket服務就ok了,node server.js跑🏃🏻‍♀️起來就可以用了

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