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

补充一个更简单的

来自 https://www.jianshu.com/p/6b870f503905
websocketService.js

var WebSocketServer = require('ws').Server,

wss = new WebSocketServer({ port: 7272 });
wss.on('connection', function (ws) {
    console.log('client connected');
    ws.send('你是第' + wss.clients.length + '位');  
    //收到消息回调
    ws.on('message', function (message) {
        console.log(message);
    	ws.send('收到:'+message);  
    });
    // 退出聊天  
    ws.on('close', function(close) {  
      	console.log('退出连接了');  
    });  
});
console.log('开始监听7272端口');

安装依赖

npm install ws
node websocketService.js

如此这般即可

posted @ 2023-05-25 20:11  CoderWGB  阅读(481)  评论(0)    收藏  举报