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();
© 版权声明
特别提醒: 内容为用户自行发布,如有侵权,请联系我们管理员删除,邮箱:mail@xieniao.com ,在收到您的邮件后我们会在3个工作日内处理。
相关文章
暂无评论...