Why doesn't "writeln" on xterm.js not work when using a socket?

241 Views Asked by At

Its really weird that when I write to the console it works but doesn't work when using socket.io.

My client:

import * as socketio from "socket.io-client";
import React, { useEffect } from "react";
import { Terminal } from "xterm";
import "xterm/css/xterm.css";
import { XTerm } from "xterm-for-react";

export default function TerminalPage() {
  return (
    <>
      <TerminalU />
    </>
  );
}

export const TerminalU = () => {
  const xtermRef = React.useRef(null);

  React.useEffect(() => {
    var term = (xtermRef.current as any).terminal as Terminal;
    // this works!
    term.writeln("hello")
    var socket = socketio.connect("ws://localhost:3000");
    socket.on("newOutput", (data) => {
      // doesn't do anything
      term.writeln(data)
      // prints to console fine
      console.log(data)

    })
  }, []);
  


  return (
    // Create a new terminal and set it's ref.
    <XTerm ref={xtermRef} options={{convertEol: true, cursorBlink: true, cursorStyle: "block",  rendererType: "canvas"}}/>
  );
};

My server:

  const io = new Server(server, {cors: {origin: "http://localhost:3006"}});
  io.on("connection", (socket) => {
    console.log(chalk.green("Creating new terminal for " + socket.id));
    var ptyProcess = pty.spawn(isWin ? "powershell.exe" : "bash", [], {
      name: "xterm-color",
      cols: 80,
      rows: 30,
      cwd: process.env.HOME,
      env: process.env,
    });
  
    ptyProcess.onData((data) => {
      socket.emit("newOutput", data);
    });
    socket.on("keyPress", (press) => {
      if (press !== null) ptyProcess.write(press);
      else ptyProcess.write("\u001B");
    });
  });

I tried putting pieces of code into functions and did alot of research. I want it so when the socket gets sent, the terminal will write it in.

1

There are 1 best solutions below

0
DeveloLongScript On

Okay, so I figured it out. You have to be using the Terminal element for Xterm and apparently xterm-for-react doesn't work with Socket.io. Weird. (if anyone else is having this problem, just don't use xterm-for-react)