Vue/前端开发

基于xterm.js 实现Vue版本终端terminal

2020-10-30  本文已影响0人  阿尔法_狗

基于xterm.js 实现Vue版本终端terminal

先看效果

image

前端实现

xterm

npm install --save xterm

xterm-addon-fit

xterm.js的插件,使终端的尺寸适合包含元素。

npm install --save xterm-addon-fit

xterm-addon-attach

xterm.js的附加组件,用于附加到Web Socket

npm install --save xterm-addon-attach

<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'

export default {
  name: 'Xterm',
  props: {
    socketURI: {
      type: String,
      default: ''
    },
  },
  mounted() {
    this.initSocket()
  },
  beforeDestroy() {
    this.socket.close()
    this.term.dispose()
  },
  methods: {
    initTerm() {
      const term = new Terminal({
        fontSize: 14,
        cursorBlink: true
      });
      const attachAddon = new AttachAddon(this.socket);
      const fitAddon = new FitAddon();
      term.loadAddon(attachAddon);
      term.loadAddon(fitAddon);
      term.open(document.getElementById('xterm'));
      fitAddon.fit();
      term.focus();
      this.term = term
    },
    initSocket() {
      this.socket = new WebSocket(this.socketURI);
      this.socketOnClose();
      this.socketOnOpen();
      this.socketOnError();
    },
    socketOnOpen() {
      this.socket.onopen = () => {
        // 链接成功后
        this.initTerm()
      }
    },
    socketOnClose() {
      this.socket.onclose = () => {
        // console.log('close socket')
      }
    },
    socketOnError() {
      this.socket.onerror = () => {
        // console.log('socket 链接失败')
      }
    }
  }
}
</script>

后端实现

node-pty

实现读取写入终端

ws

node socket

npm install --save wx

代码

const pty = require('node-pty');
const os = require('os');
const WebSocket = require('ws');
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';

const wss = new WebSocket.Server({port: 4001});

wss.on('connection', (ws) => {
  console.log('socket connection success');
  const ptyProcess = pty.spawn(shell, [], {
    name: 'xterm-color',
    cols: 80,
    rows: 30,
    cwd: process.env.HOME,
    env: process.env
  });
  //接受数据
  ws.on('message', (res) => {
    ptyProcess.write(res)
  });
  //发送数据
  ptyProcess.on('data', function (data) {
    process.stdout.write(data);
    ws.send(data)
  });
});

上一篇下一篇

猜你喜欢

热点阅读