vnc和node.js实现web远程桌面的完整步骤(2)

/** * VNC连接 */ private VNCConnect(): void { /** 访问 /vnc/ websocket */ const url = `ws://${this.host}/vnc/${this.ip}:${this.port}`; /** 新建远程控制对象 */ this.rfb = new RFB(this.container.nativeElement, url, { credentials: { password: this.password, }, }); /** 添加connect事件监听器 */ this.rfb.addEventListener('connect', () => { this.rfb.focus(); }); }

nginx 转发

nginx监听本地的8013端口。

ws://127.0.0.1:8013/vnc/192.168.0.104:5900请求发给了nginx,根据前缀匹配,以/vnc/开头的转发给8112端口。

location /vnc/ { proxy_pass :8112/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; }

node.js 转发

node.js监听8112端口,处理当前的websocket请求。

/** 建立基于 vnc_port 的 websocket 服务器 */ const vnc_server = http.createServer(); vnc_server.listen(vnc_port, function () { const web_socket_server = new WebSocketServer({server: vnc_server}); web_socket_server.on('connection', web_socket_handler); });

转发的核心代码在方法web_socket_handler中,以下是完整代码:

这里说一句,之前写的注释都不规范,所有注释都应该是文档注释,单行注释使用/** 内容 */的格式。

/** 引入 http 包 */ const http = require('http'); /** 引入 net 包 */ const net = require('net'); /** 引入 websocket 类 */ const WebSocketServer = require('ws').Server; /** 本机 ip 地址 */ const localhost = '127.0.0.1'; /** 开放的 vnc websocket 转发端口 */ const vnc_port = '8112'; /** 打印提示信息 */ console.log(`成功创建 WebSocket 代理 : ${localhost} : ${vnc_port}`); /** 建立基于 vnc_port 的 websocket 服务器 */ const vnc_server = http.createServer(); vnc_server.listen(vnc_port, function () { const web_socket_server = new WebSocketServer({server: vnc_server}); web_socket_server.on('connection', web_socket_handler); }); /** websocket 处理器 */ const web_socket_handler = function (client, req) { /** 获取请求url */ const url = req.url; /** 截取主机地址 */ const host = url.substring(url.indexOf('https://www.jb51.net/') + 1, url.indexOf(':')); /** 截取端口号 */ const port = Number(url.substring(url.indexOf(':') + 1)); /** 打印日志 */ console.log(`WebSocket 连接 : 版本 ${client.protocolVersion}, 协议 ${client.protocol}`); /** 连接到 VNC Server */ const target = net.createConnection(port, host, function () { console.log('连接至目标主机'); }); /** 数据事件 */ target.on('data', function (data) { try { client.send(data); } catch (error) { console.log('客户端已关闭,清理到目标主机的连接'); target.end(); } }); /** 结束事件 */ target.on('end', function () { console.log('目标主机已关闭'); client.close(); }); /** 错误事件 */ target.on('error', function () { console.log('目标主机连接错误'); target.end(); client.close(); }); /** 消息事件 */ client.on('message', function (msg) { target.write(msg); }); /** 关闭事件 */ client.on('close', function (code, reason) { console.log(`WebSocket 客户端断开连接:$[code] [${reason}]`); target.end(); }); /** 错误事件 */ client.on('error', function (error) { console.log(`WebSocket 客户端出错:${error}`); target.end(); }); };

总结

为了这个功能犯愁了半个月,觉也睡不好,客户都在腾讯云上看到过的功能,写不出来就特别的难受,如今终于圆满解决。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ce81492f1804847d28c98d4b71c2ce6b.html