Created
November 7, 2023 09:35
-
-
Save gabonator/811f112a3eab81d426433519a4e5dfad to your computer and use it in GitHub Desktop.
Websockets with nodejs express server using single port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/xterm.css"/> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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