Node.js实现websocket服务器,转换UDP数据

随笔1个月前发布 猫圆子
33 0 0

Node.js实现websocket服务器,转换UDP数据

const dgram = require('dgram');

function udp_server() {
  const server = dgram.createSocket('udp4');

  server.on('error', (err) => {
    console.error(`server error:
${err.stack}`);
  });

  server.on('message', (msg, rinfo) => {
    console.log(msg.toString());
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(msg.toString());
      }
    });

  });

  server.on('listening', () => {
  });

  server.bind(12388);
}
udp_server();

const WebSocket = require('ws');
const readline = require('readline');

// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 1919 });

// 监听WebSocket连接事件
wss.on('connection', (ws, req) => {
  const clientIp = req.socket.remoteAddress;
  const clientPort = req.socket.remotePort;
  console.log(`客户端已连接,[${clientIp}]:${clientPort}`);

  // 监听WebSocket消息事件
  ws.on('message', (message) => {
    console.log(`收到来自 [${clientIp}]:${clientPort} 的消息: ${message}`);
  });
  
  // 监听WebSocket关闭事件
  ws.on('close', () => {
    console.log(`客户端 [${clientIp}]:${clientPort} 已断开连接`);
  });
});


// 创建一个用于从控制台读取输入的接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "========
"
});

// 监听控制台输入事件
rl.on('line', (input) => {
  // 遍历所有连接的客户端并发送消息
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(input);
    }
  });

  // 显示输入提示符
  rl.prompt();
});

console.log('WebSocket服务器已启动,监听端口 1919');
rl.prompt();

 

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...