溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

react?express怎么實(shí)現(xiàn)webssh?demo解析

發(fā)布時間:2023-04-04 14:22:37 來源:億速云 閱讀:135 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“react express怎么實(shí)現(xiàn)webssh demo解析”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

實(shí)現(xiàn) WebSSH 的基本思路

WebSSH 可以分成以下幾個模塊:

  • 前端界面:使用 xterm.js 實(shí)現(xiàn)一個基于瀏覽器的終端界面。

  • WebSocket 連接:使用 WebSocket 連接連接 WebSSH 服務(wù)器后端。

  • SSH 連接:使用 ssh3.js 庫連接 SSH 服務(wù)器,然后在 WebSocket 和 SSH 之間建立一個雙向通訊。

實(shí)現(xiàn) Demo 的代碼

服務(wù)器端代碼

服務(wù)器端代碼使用 Node.js 和 WebSocket 模塊實(shí)現(xiàn),主要用于連接到遠(yuǎn)程 SSH 服務(wù)器并與前端建立 WebSocket 連接。

const SSHClient = require('ssh3').Client;
const utf8 = require('utf8');
export const createNewServer = (machineConfig: any, socket: any) => {
  const ssh = new SSHClient();
  const { host, username, password } = machineConfig;
  // 連接成功
  ssh.on('ready', function () {
    socket.send('\r\n*** SSH CONNECTION SUCCESS ***\r\n');
    ssh.shell(function (err: any, stream: any) {
      // 出錯
      if (err) {
        return socket.send('\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
      }
      // 前端發(fā)送消息
      socket.on('message', function (data: any) {
        stream.write(data);
      });
      // 通過sh發(fā)送消息給前端
      stream.on('data', function (d: any) {
        socket.send(utf8.decode(d.toString('binary')));
        // 關(guān)閉連接
      }).on('close', function () {
        ssh.end();
      });
    })
    // 關(guān)閉連接
  }).on('close', function () {
    socket.send('\r\n*** SSH CONNECTION CLOSED ***\r\n');
    // 連接錯誤
  }).on('error', function (err: any) {
    socket.send('\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
    // 連接
  }).connect({
    port: 22,
    host,
    username,
    password
  });
}

前端代碼

前端代碼主要包括一個包裝 xterm.js 的 React 組件和一些 WebSockets 相關(guān)的代碼。

import React, { useEffect, useRef } from 'react';
import { Terminal } from 'xterm';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { FitAddon } from 'xterm-addon-fit';
import 'xterm/css/xterm.css';
const FontSize = 14;
const Col = 80;
const WebTerminal = () => {
  const webTerminal = useRef(null);
  const ws = useRef(null);
  useEffect(() => {
    // 初始化終端
    const ele = document.getElementById('terminal');
    if (ele && !webTerminal.current) {
      const height = ele.clientHeight;
      // 初始化
      const terminal = new Terminal({
        cursorBlink: true,
        cols: Col,
        rows: Math.ceil(height / FontSize),
      });
      // 輔助
      const fitAddon = new FitAddon();
      terminal.loadAddon(new WebLinksAddon());
      terminal.loadAddon(fitAddon);
      terminal.open(ele);
      terminal.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
      fitAddon.fit();
      webTerminal.current = terminal;
    }
    // 初始化ws連接
    if (ws.current) ws.current.close();
    const socket = new WebSocket('ws://localhost:3001');
    socket.onopen = () => {
      socket.send('connect success');
    };
    ws.current = socket;
  }, []);
  useEffect(() => {
    // 新增監(jiān)聽事件
    const terminal = webTerminal.current;
    const socket = ws.current;
    if (terminal && socket) {
      // 監(jiān)聽
      terminal.onKey(e => {
        const { key } = e;
        socket.send(key);
      });
      // ws監(jiān)聽
      socket.onmessage = e => {
        console.log(e);
        if (typeof e.data === 'string') {
          terminal.write(e.data);
        } else {
          console.error('格式錯誤');
        }
      };
    }
  }, []);
  return <div id="terminal"  style={{ backgroundColor: '#000', width: '100vw', height: '100vh' }}/>;
};
export default WebTerminal;

WebSSH 組件借助 Hooks 特性進(jìn)行 WebSocket 和 xterm.js 的初始化。具體來說,這個組件使用了 useEffect Hook 在組件掛載時完成以下工作:

  • 初始化 Terminal 組件。

  • 初始化 WebSocket 連接。

  • 為 Terminal 組件綁定輸入事件和 WebSocket 發(fā)送數(shù)據(jù)的邏輯。

在 React 應(yīng)用中使用 WebSSH 組件

你需要在你的 React的index.js 文件中引入 WebSSH 組件,并在你的應(yīng)用中渲染它:

import WebSSH from './components/WebSSH';
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
  <WebSSH />,
  document.getElementById('root')
);

效果

react?express怎么實(shí)現(xiàn)webssh?demo解析

“react express怎么實(shí)現(xiàn)webssh demo解析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI