xterm+vue+websocket
Preparação
-
ambiente vue
-
instalação do node.js.
-
instalar webpack
-
instalação de andaimes vue
-
-
Introdução de plug-ins relacionados ao xterm
-
termo x
-
xterm-addon-fit
-
xterm-addon-search
-
preparar
<template>
<div id="xterm" class="xterm" />
</template>
<script>
import 'xterm/css/xterm.css'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { AttachAddon } from 'xterm-addon-attach'
import 'xterm/lib/xterm.js'
export default {
name: 'Terminal',
data() {
return {
term: '',
socketURI: 'ws://127.0.0.1:8081/ws',
rows: 30,
cols: 40
}
},
mounted() {
this.initSocket()
},
beforeDestroy() {
this.socket.close()
this.term.dispose()
},
methods: {
initTerm() {
const _this = this // 一定要重新定义一个this,不然this指向会出问题
this.term = new Terminal({
fontSize: 23, // 字体
cursorBlink: true, // 光标闪烁
disableStdin: false, // 是否应禁用输入
convertEol: true, // 启用时,光标将设置为下一行的开头
scrollback: 10, // 终端中的回滚量
rows: _this.rows,
cols: _this.cols,
theme: {
foreground: 'yellow', // 字体颜色
screenKeys: true
}
})
const attachAddon = new AttachAddon(this.socket)
const fitAddon = new FitAddon()
this.term.loadAddon(attachAddon)
this.term.loadAddon(fitAddon)
this.term.open(document.getElementById('xterm'))
fitAddon.fit()
this.term.focus()
this.term.onKey(e => {
const printable = !e.domEvent.altKey && !e.domEvent.altGraphKey && !e.domEvent.ctrlKey && !e.domEvent.metaKey
if (e.domEvent.keyCode === 13) {
_this.send(e.key)
} else if (e.domEvent.keyCode === 8) {
if (_this.term._core.buffer.x > 2) {
_this.term.write('\b ')
_this.send(e.key)
}
} else if (printable) {
// _this.term.write(e.key)
_this.send(e.key)
} else {
_this.send(e.key)
}
})
},
initSocket() {
this.socket = new WebSocket(this.socketURI)
this.socketOnClose()
this.socketOnOpen()
this.socketOnError()
this.getMessage()
},
socketOnOpen() {
this.socket.onopen = () => {
// 链接成功后
console.log('socket 连接成功')
this.initTerm()
}
},
socketOnClose() {
this.socket.onclose = () => {
console.log('socket关闭')
this.socket.close()
}
},
socketOnError() {
this.socket.onerror = () => {
console.log('socket 链接失败')
}
},
send(order) {
console.log('发送' + order)
this.socket.send(Buffer.concat([new Buffer([0]), new Buffer(order)]))
},
getMessage() {
this.socket.onmessage = function(evt) {
console.log('响应数据:' + evt.data)
}
}
}
}
</script>
<style scoped>
</style>
anotação:
A estrutura de dados enviada na função send(order) no websocket é a estrutura de dados especificada pelos front-ends e back-ends
Fonte de aprendizagem: