vue3 webssh終端實現-基於xterm.js

一、xterm介紹

xterm是一個使用 TypeScript 編寫的前端終端組件,可以直接在瀏覽器中實現一個命令行終端應用,通常與websocket一起使用。

--------------------------順便吐個槽:官方文檔太簡陋,啥都需要看代碼 -_- --------------------------

二、xterm插件介紹
  • FitAddon:調整終端的大小,以適合父元素的大小。
  • AttachAddon:將終端附加到 WebSocket 流,與後臺進行交互。


如果想使用這個插件,最好看下默認的WebSocket 實現是否是符合需要,需要定製化的可能不太適用。
比如:message 使用addEventListener監聽事件實現,這意味着 AttachAddon默認的監聽事件覆蓋不了,會輸出所有data
而我的項目需求是展示data裏面的部分信息,所以默認的WebSocket用不了了,這個插件也就用不了,需要自己實現一個websocket

三、webssh終端實現

經過不斷的摸索和嘗試,有了初步的終端實現:

<template>
    <div
        v-loading="loading"
        ref="terminal"
        element-loading-text="拼命連接中"
    ></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import { debounce } from 'lodash'
import { Terminal } from "xterm";
import { FitAddon } from "xterm-addon-fit";
import "xterm/css/xterm.css";

const terminal = ref(null);
const props = defineProps({
    terminalDetail: Object,
    type: String
});
const fitAddon = new FitAddon();

let first = ref(true);
let loading = ref(true);
let terminalSocket = ref(null);
let term = ref(null);


const runRealTerminal = () => {
    loading.value = false;
}

const onWSReceive = (message) => {
    // 首次接收消息,發送給後端,進行同步適配
    if (first.value === true) {
        first.value = false;
        resizeRemoteTerminal();
    }
    const data = JSON.parse(message.data);
    term.value.element && term.value.focus()
    term.value.write(data.Data)
}

const errorRealTerminal = (ex) => {
    let message = ex.message;
    if (!message) message = 'disconnected'
    term.value.write(`\x1b[31m${message}\x1b[m\r\n`)
    console.log("err");
}
const closeRealTerminal = () => {
    console.log("close");
}

const createWS = () => {
    const url = 'XXXX' 
    terminalSocket.value = new WebSocket(url);
    terminalSocket.value.onopen = runRealTerminal;
    terminalSocket.value.onmessage = onWSReceive;
    terminalSocket.value.onclose = closeRealTerminal;
    terminalSocket.value.onerror = errorRealTerminal;
}
const initWS = () => {
    if (!terminalSocket.value) {
        createWS();
    }
    if (terminalSocket.value && terminalSocket.value.readyState > 1) {
        terminalSocket.value.close();
        createWS();
    }
}
// 發送給後端,調整後端終端大小,和前端保持一致,不然前端只是範圍變大了,命令還是會換行
const resizeRemoteTerminal = () => {
    const { cols, rows } = term.value
    if (isWsOpen()) {
        terminalSocket.value.send(JSON.stringify({
            Op: 'resize',
            Cols: cols,
            Rows: rows,
        }))
    }
}
const initTerm = () => {
    term.value = new Terminal({
        lineHeight: 1.2,
        fontSize: 12,
        fontFamily: "Monaco, Menlo, Consolas, 'Courier New', monospace",
        theme: {
            background: '#181d28',
        },
        // 光標閃爍
        cursorBlink: true,
        cursorStyle: 'underline',
        scrollback: 100,
        tabStopWidth: 4,
    });
    term.value.open(terminal.value);
    term.value.loadAddon(fitAddon);
   // 不能初始化的時候fit,需要等terminal準備就緒,可以設置延時操作
    setTimeout(() => {
        fitAddon.fit();
    }, 5)
}
// 是否連接中0 1 2 3 
const isWsOpen = () => {
    const readyState = terminalSocket.value && terminalSocket.value.readyState;
    return readyState === 1
}
const fitTerm = () => {
    fitAddon.fit();
}
const onResize = debounce(() => fitTerm(), 800);

const termData = () => {
    // 輸入與粘貼的情況,onData不能重複綁定,不然會發送多次
    term.value.onData(data => {
        if (isWsOpen()) {
            terminalSocket.value.send(
                JSON.stringify({
                    Op: 'stdin',
                    Data: data,
                })
            );
        }
    });
}
const onTerminalResize = () => {
    window.addEventListener("resize", onResize);
}
const removeResizeListener = () => {
    window.removeEventListener("resize", onResize);
}
//監聽類型變化,重置term
watch(() => props.type, () => {
    first.value = true;
    loading.value = true;
    terminalSocket.value = null;
    initWS();
    // 重置
    term.value.reset();
})

onMounted(() => {
    initWS();
    initTerm();
    termData();
    onTerminalResize();
})
onBeforeUnmount(() => {
    removeResizeListener();
    terminalSocket.value && terminalSocket.value.close();
})
</script>
<style lang="scss" scoped>
#terminal {
    width: 100%;
    height: 100%;
}
</style>
遇到的問題

1、websocket連接成功後,前端輸入命令在message裏不輸出,websocket readyState 會從1 ( connect )轉成3( close )

之前沒看AttachAddon的默認實現,就自動給term loadAddonAttachAddon,使用了默認的websocket,自己實現的被覆蓋了,導致剛連成功websocket 的狀態從1變成了3,去掉了就好了。

2、終端自適應問題


  • fitAddon.fit() 的問題:不能初始化的時候調用,需要設置延時
  • websocket進行通信時發現命令都是換行的,查找資料後發現沒有和後端同步頁面顯示的命令行大小,需要發送同步消息resizeRemoteTerminal哦。
  • 前端自適應(resize)的時候也是要和後端同步的,fitAddon.fit()後需要走onResize方法同步

3、終端釋放問題
onBeforeUnmount 最後加上term.value&&term.value.dispose()總是會釋放失敗,可能不需要釋放吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章