Skip to content

Instantly share code, notes, and snippets.

@gabonator
Created November 7, 2023 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabonator/811f112a3eab81d426433519a4e5dfad to your computer and use it in GitHub Desktop.
Save gabonator/811f112a3eab81d426433519a4e5dfad to your computer and use it in GitHub Desktop.
Websockets with nodejs express server using single port
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css"/>
<script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.js"></script>
<div id="terminal">
<script>
var terminal = new window.Terminal({cursorBlink: true});
terminal.open(document.querySelector('#terminal'));
terminal.onData(e => socket.send(e));
var socket = new WebSocket(document.location.href.split("http").join("ws") + "terminal");
socket.onmessage = msg => terminal.write(msg.data);
socket.onopen = () => {
console.log("socket opened");
terminal.focus();
}
socket.onclose = () => console.log("socket closed");
</script>
const express = require('express');
const protocol = require("http");
const app = express();
const ws = require('ws');
const child_process = require('child_process');
const websocket = new ws.Server({ noServer: true, rejectUnauthorized: false })
const port = 9999;
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get("/terminal", (req, res) => {
websocket.handleUpgrade(req, req.socket, req.headers, socket => {
websocket.emit('connection', socket);
});
return true;
});
app.get('*', (req, res) => {
res.sendFile(__dirname + "/" + req.params[0]);
});
protocol.createServer(app).listen(port, () => {
console.log(`Server listening at port ${port}`)
})
websocket.on("connection", conn => {
console.log("Websocket connected")
var shell = child_process.spawn("podman", "run -it ubuntu bash".split(" "));
shell.stdout.setEncoding('utf8')
shell.stdout.on("data", data => conn.send(data));
conn.on("message", data => shell.stdin.write(data));
conn.on("close", () => {
console.log("Websocket disconnected");
shell.stdin.pause();
shell.kill();
});
conn.onerror = function () {
console.log("Websocket comm error")
shell.stdin.pause();
shell.kill();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment