xterm+vue+websocket
准备工作
-
vue环境
-
node.js安装
-
webpack安装
-
vue脚手架安装
-
-
xterm相关插件引入
-
xterm
-
xterm-addon-fit
-
xterm-addon-search
-
就绪
<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>
批注:
websocket中send(order)函数中发送的数据结构为前后端指定的数据结构
学习来源: