From 69ef435b77b3e92fa1f878e2dfa79540f1aa7958 Mon Sep 17 00:00:00 2001 From: wancat Date: Sat, 15 Jul 2023 14:36:51 +0800 Subject: [PATCH] Success to execute and show output using Websocket --- server/client.js | 2 +- server/docker.js | 28 +++++++++------------------- server/websocket.js | 10 +++++++++- 3 files changed, 19 insertions(+), 21 deletions(-) diff --git a/server/client.js b/server/client.js index efaa75e..5b7090b 100644 --- a/server/client.js +++ b/server/client.js @@ -14,7 +14,7 @@ socket.on('open', function open() { }) socket.on('message', function incoming(data) { - console.log(`From server: ${data}`) + console.log(`${data}`) }) socket.on('close', function close() { diff --git a/server/docker.js b/server/docker.js index dc03fb2..e2eaf44 100644 --- a/server/docker.js +++ b/server/docker.js @@ -13,10 +13,11 @@ const containerOptions = { StdinOnce: false, } -async function createContainer() { +export async function createContainer() { try { const container = await engine.createContainer(containerOptions) await container.start() + console.log(container.id) return container } catch (error) { console.error(error) @@ -24,23 +25,12 @@ async function createContainer() { } } -async function attachContainer() { - const container = await createContainer() - console.log(container.id) +export async function attachContainer(container) { // Create an exec instance with bash shell - - container.attach( - { - stream: true, - stdin: true, - stdout: true, - stderr: true, - ws: true, - }, - (err, stream) => { - stream.pipe(process.stdout) - } - ) + return container.attach({ + stream: true, + stdin: true, + stdout: true, + stderr: true, + }) } - -attachContainer() diff --git a/server/websocket.js b/server/websocket.js index c3ffc60..761f364 100644 --- a/server/websocket.js +++ b/server/websocket.js @@ -1,16 +1,24 @@ import express from 'express' import http from 'http' import { Server } from 'socket.io' +import { createContainer, attachContainer } from './docker.js' const app = express() const server = http.createServer(app) const io = new Server(server) -io.on('connection', (socket) => { +io.on('connection', async (socket) => { console.log('Connected to the client.') + const container = await createContainer() + const stream = await attachContainer(container) + + stream.on('data', (chunk) => { + socket.send(chunk.toString()) + }) socket.on('message', function incoming(message) { console.log(`From client: ${message}`) + stream.write(message + '\n') }) socket.on('close', () => {