k8s的容器的webssh實現
Vite2.x + Vue3.x + Xtermjs4
相關信息
- 編程語言:TypeScript 4.x + JavaScript
- 構建工具:Vite 2.x
- 前端框架:Vue 3.x
- 路由工具:Vue Router 4.x
- 狀態管理:Vuex 4.x
- UI 框架:Element Plus
- CSS 預編譯:Stylus / Sass / Less
- HTTP 工具:Axios
安裝依賴
npm install
# or
yarn add
啟動項目
npm run dev
項目打包
npm run build
功能完成
2021/6/8
具體代碼在:https://github.com/haozheyu/k8sResourceDisplay
排坑不易,大家給給?※?,好讓我在排坑的路上樂此不疲
<template>
<div ref="terminal" id="terminal"></div>
</template>
<script>
import {defineComponent, reactive, toRefs, onMounted, ref, markRaw, onBeforeUnmount, onUnmounted} from 'vue'
import { useRouter } from 'vue-router'
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import 'xterm/css/xterm.css'
import { ElMessage } from 'element-plus'
export default defineComponent({
name: 'Xterm',
setup(){
//實例化路由
const shellWs = ref(null)
const rows = ref(null)
const cols = ref(null)
const term = new Terminal({
rendererType: 'canvas',
cursorBlink: true,
convertEol: true,
scrollback: 800,
row: 70,
theme: {
foreground: 'white',
background: '#181E29'
}
})
const fitAddon = new FitAddon();
// canvas背景全屏
term.loadAddon(fitAddon);
fitAddon.fit();
const router = useRouter();
const podName = router.currentRoute.value.query.podName
const podNamespace = router.currentRoute.value.query.podNamespace
const containerName = router.currentRoute.value.query.containerName
const SHELL = router.currentRoute.value.query.shell
const querystring = "ws://localhost:8080/resource/websocket?" + "podNs="+ podNamespace + "&podName=" + podName + "&containerName=" + containerName + "&shell=" + SHELL
const ws = new WebSocket(querystring)
onMounted(()=>{
term.open(document.getElementById('terminal')); //綁定dom節點
term.focus() // 取得輸入焦點
term.writeln('Connecting...'); // 寫一行測試
ws.onclose = function (e) {
ElMessage.warning({
message: '鏈接已關閉',
type: 'warning',
center: true,
});
}
ws.onmessage = function (e) { // 服務端ssh輸出, 寫到web shell展示
term.write(e.data)
}
ws.onerror = function (e) {
ElMessage.error({
message: '請更換,shell環境再試一下',
type: 'error',
center: true,
});
}
// 當瀏覽器窗口變化時, 重新適配終端
window.addEventListener("resize", function () {
fitAddon.fit();
// 把web終端的尺寸term.rows和term.cols發給服務端, 通知sshd調整輸出寬度
var msg = {type: "resize", rows: term.rows, cols: term.cols}
ws.send(JSON.stringify(msg))
})
// 當向web終端敲入字符時候的回調
// term.onKey(e => { //給后端發送數據
// // 寫給服務端, 由服務端發給container
// console.log(e.key)
// var msg = {type: "input", input: e.key }
// ws.send(JSON.stringify(msg))
// })
// 支持輸入與粘貼方法
term.onData(function(input) {
// 寫給服務端, 由服務端發給container
var msg = {type: "input", input: input}
ws.send(JSON.stringify(msg))
})
})
onUnmounted(()=>{
ws.close()
})
return {
shellWs, term, rows, cols
}
},
})
</script>
<style>
</style>

如果當你發現自己的才華撐不起野心時,那就請你安靜下來學習

浙公網安備 33010602011771號