使用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跑🏃🏻‍♀️起来就可以用了

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