I am currently building a basic web-based platform for Java coders, where users can submit their code to solve a given problem statement. I have implemented the front-end code using** HTML and JavaScript**, and the back-end server-side code using Express.js and child_process. However, I am facing issues with executing Java programs that require user input during runtime.
**
Here is a summary of my setup:**
Front-end: I have a form with a textarea where users can enter their Java code. Upon submission, the code is sent to the server for execution.
Server-side: The server receives the code, writes it to a temporary Java source file, and then uses spawn to execute the Java program. If the code compilation is successful, it proceeds to execute the compiled Java class.
Issue: The execution is working fine for Java programs without user input. However, for programs that require user input during runtime, I am not able to provide the input from the server side and receive the output on the front-end.
Here is an example of a Java program that requires user input:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: " + sum);
}
}
Here is the Front End Code and Backend server code.
Front End code
<!DOCTYPE html>
<html>
<head>
<title>Code Submission Platform</title>
<style>
#codeForm {
margin-top: 20px;
}
label {
display: block;
margin-bottom: 10px;
}
textarea {
width: 100%;
height: 200px;
}
button {
margin-top: 10px;
}
#result {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Code Submission Platform</h1>
<form id="codeForm">
<label for="code">Enter your code:</label>
<textarea id="code" name="code" placeholder="Enter your code here"></textarea>
<button type="submit">Submit</button>
</form>
<div id="result"></div>
<script>
const form = document.getElementById('codeForm');
const resultDiv = document.getElementById('result');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Get the code from the textarea
const code = document.getElementById('code').value;
// Send the code to the backend API
// Replace `API_URL` with the actual URL of your backend API
fetch('http://localhost:3000/compile', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ code })
})
.then(response => response.json())
.then(data => {
// Display the result in the resultDiv
resultDiv.innerHTML = `<h2>Result:</h2><pre>${data.result}</pre>`;
})
.catch(error => {
console.error('Error:', error);
resultDiv.innerHTML = '<h2>Error:</h2><p>Something went wrong. Please try again later.</p>';
});
});
</script>
</body>
</html>
And here is the Backend code.
const express = require('express');
const { spawn } = require('child_process');
const app = express();
const port = 3000;
app.use(express.json()); // Parse JSON request bodies
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// Endpoint to handle code submission
app.post('/compile', (req, res) => {
const { code } = req.body; // Assuming the code is sent as a JSON object with a "code" property
if (!code) {
res.status(400).send({ error: 'Code is missing' });
return;
}
// Create a temporary Java source file
const sourceFilePath = '/Users/shubham/Desktop/Coding Tool/HelloWorld.java';
const fs = require('fs');
fs.writeFileSync(sourceFilePath, code);
// Run the Java compiler
const compiler = spawn('javac', [sourceFilePath]);
// Handle the compiler output
compiler.stdout.on('data', data => {
console.log(`Compiler output: ${data}`);
});
compiler.stderr.on('data', data => {
console.error(`Compiler error: ${data}`);
});
compiler.on('close', code => {
if (code === 0) {
// Execute the compiled Java class file
const execution = spawn('java', ['-cp', '/Users/shubham/Desktop/Coding Tool', 'HelloWorld']);
let executionOutput = '';
execution.stdout.on('data', data => {
executionOutput += data.toString();
});
execution.stderr.on('data', data => {
console.error(`Execution error: ${data}`);
});
execution.on('close', code => {
console.log('Sending response:', executionOutput);
res.send({ result: executionOutput });
});
} else {
console.log('Sending response: Compilation failed!');
res.send({ result: 'Compilation failed!' });
}
});
});
// Start the server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
I have tried passing the input from the front-end to the server and then sending it to the Java program, but I’m not getting any output in response.
I would appreciate any insights or suggestions on how to handle user input for Java programs in my web-based code submission platform. How can I modify my server-side code to handle user input during runtime and receive the output on the front-end?
Thank you in advance for your help!
I was Expecting the Output 10 as result of First number 5 and Second Number 5 and returned back to frontend, but this inputs should be stored in server side, and if there is program with no input require it should work as it is.