gpt4 book ai didi

c# - 使用 ServiceStack 将命令输出流式传输到 ajax 调用

转载 作者:行者123 更新时间:2023-11-30 23:08:33 25 4
gpt4 key购买 nike

我有一个 ServiceStack 服务,它在给定输入文件的情况下执行长时间运行(例如 10-20 秒)的程序。在客户端,文件被上传到服务,然后文件被传递给可执行文件。我能够将该可执行文件的输出重定向到一个流,但是当我尝试将该流发送到我在客户端的 ajax 调用时,直到流完成它才开始使用。我认为我已经正确地完成了所有设置部分内容的工作,所以我不确定为什么这不起作用(或者这是否可以通过服务器端的 ServiceStack 和 jQuery 的 ajax 实现)在客户端调用)。我的代码如下(略作修改以删除任何专有内容。尽管适用相同的原则):

//Service side
public async Task<HttpResult> Post(SomeProcessingRequest request) {
var tempFile = Path.GetTempFileName();
try {
base.Request.Files.FirstNonDefault().SaveTo(tempFile);
log.Info($@"Launching application");
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var result = new HttpResult(ms, "text");
//launches the app and pipes the output to the lambda (just a wrapper for Process)
await env.LaunchApplication("myapp.exe", false, (msg) => {
if (msg != null) {
ms.Write(msg);
ms.Flush();
}
}, (msg) => {}, () => { }, () => { throw new Exception("application failed"); }, $@"-i {tempFile}");
log.Info($@"app complete");
return result;
} finally {
try {
File.Delete(tempFile);
} catch(IOException ex) {
log.Warn($@"Could not delete temp file {tempFile}");
}
}
}

客户端ajax调用:

this.ImportCommand = (element, event) => {
var last_response_len = false;
var fileInput = $('#fileInput');
var file = fileInput.get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: `/*url here*/`,
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: (res) => {
console.log("app call complete");
self.RefreshCommand();
},
xhrFields: {
onprogress: (e) => {
console.log(e.currentTarget.response);
var this_response, response = e.currentTarget.response;
if (last_response_len === false) {
this_response = response;
last_response_len = response.length;
} else {
this_response = response.substring(last_response_len);
last_response_len = response.length;
}
self.outputLog += this_response;
}
}
});

因此,一切似乎都正常工作,除了不是实时流式传输命令的输出,而是将其全部添加到流中,然后在响应来自服务器时转储流。我试图通过 ServiceStack/jQuery 实现的目标是什么?本质上,我想显示一些类似于 Jenkins 构建日志实时更新的内容。

最佳答案

感谢 Petah 在这里的评论,我弄明白了:jquery ajax, read the stream incrementally?

问题是它一次写出的字节少于 2048 个字节。只是为了好玩和咯咯笑,我创建了一个 4096 字节的数组并将其写出多次, sleep 了几次,果然它按预期工作了。我花在这上面的时间比我应该花的时间要长很多...

关于c# - 使用 ServiceStack 将命令输出流式传输到 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com