我有一个Web应用程序,它接受来自客户端(浏览器)的输入,并使用输入调用服务器端的应用程序。问题是应用程序将运行很长时间(大约20秒)。为了不阻止客户端(浏览器)并向用户显示进度,我的服务器端POST函数立即返回并为用户提供信息 输入到应用程序。一旦应用程序计算了结果,我就使用socket.io将结果发送到客户端。该场景的另一个变化是应用程序无法重复启动和关闭(将导致CUDA出现问题),因此整个服务器端只运行应用程序的一个实例。我的服务器端代码草图如下所示。嵌入在代码中的是我通过互联网搜索过的三个问题并尝试了各种解决方案,但无法解决。对他们的任何帮助都非常感谢。如果这不是一个正确的问题,我会感谢任何关于在哪里提出这个问题的反馈。
var express = require('express');
const{ spawn }= require('child_process');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var darknet = spawn('./darknet', other arguments...) ;
io.on('connection', function(socket){
app.socket = socket;
console.log('A connection has been established');
})
darknet.stdout.on('data',(data) =>{
// This function is called once darknet finished computation and wrote the result to the stdout
// Question 1: now need to send the data back to the client but have no access to any socket here?
})
io.on('connection', function(socket){
//Question 2: how to store this socket so that I can use it in a solution to the Question 1? Can I use session? */
//Question 3: I observed that once the client side refreshed its page (for example, uploaded an image), the previous socket will be closed and a new socket will be established. How do I make sure that I send the output from the application to the right socket since the original one may be invalid when the output is ready to be sent?
})
app.post('/predict', function (req,res){
darknet.stdin.write(user_input+'\n');
res.render();
})