no-vnc和node.js实现web远程桌面的完整步骤

2020-06-17 06:58:36易采站长站整理

no-vnc

官网链接:noVNC

安装依赖:


npm install @novnc/novnc

前台组件

一个空div,同时在组件中引用。


<div class="container" #container>
</div>


@ViewChild('container')
private container: ElementRef<HTMLDivElement>;

核心的代码其实就这几行,所有协议的细节都被封装在no-vnc中的RFB类中了。

所有描述以访问192.168.0.104主机的5900端口为例,websocket地址为:ws://127.0.0.1:8013/vnc/192.168.0.104:5900。


/**
* 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 http://127.0.0.1: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;