I am trying to create a terminal that you can use in a browser to run programs, similar to replit.com where you can run code in the browser and interact with the program. So far I've created a JS client and a Python server. The JS client looks like this:
var server = new WebSocket("ws://localhost:8001");
$(document).ready(function () {
$("input").on("keydown", function search(e) {
if (e.keyCode == 13) {
server.send($(this).val());
}
});
server.onmessage = function (event) {
$("#result").append(event.data.replaceAll("\n", "<br>") + "<br>");
};
});
Which connects to the server, sends all commands and receives all output.
The server looks like this:
#!/usr/bin/env python
import asyncio
import websockets
import subprocess
async def handler(websocket, _):
while True:
message = await websocket.recv()
message = message.split()
try:
output = subprocess.run(
[*message], stdout=subprocess.PIPE).stdout.decode('utf-8')
await websocket.send(output)
except:
await websocket.send("Command error")
async def main():
async with websockets.serve(handler, "", 8001):
await asyncio.Future()
asyncio.run(main())
This works for running one off commands, but not if I want to run a Python program and interact with it. Is there any way for me to do that?