【发布时间】:2015-12-18 15:31:38
【问题描述】:
问题
我正在尝试将一些数据上传到网络服务。
我想上传数据in chunks,并让网络服务依次读取每个块。但是,我在实践中发现 Web 服务一次只会读取一个完整的缓冲区。
有没有办法让 WebAPI(理想情况下由 Owin 自托管运行,但如果需要我可以使用 IIS)来尊重传输块?
我已在 Wireshark 中验证我的客户端正在发送分块数据,因此我认为这是一个 WebAPI 问题。
为了清楚起见,响应中的流数据工作得很好——我的问题是关于从请求流中读取分块数据。
代码
控制器如下所示:
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
public class StreamingController : ApiController
{
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
var stream = await this.Request.Content.ReadAsStreamAsync();
var data = new byte[20];
int chunkCount = 1;
while (true)
{
// I was hoping that every time I sent a chunk, then
// ReadAsync would return, but I find that it will only
// return when I have sent 20 bytes of data.
var bytesRead = await stream.ReadAsync(data, 0, data.Length);
if (bytesRead <= 0)
{
break;
}
Console.WriteLine($"{chunkCount++}: {Encoding.UTF8.GetString(data)}");
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
我的测试客户端如下所示:
void Main()
{
var url = "http://localhost:6001/streaming/upload";
var relayRequest = (HttpWebRequest)HttpWebRequest.Create(url);
relayRequest.Method = "POST";
relayRequest.AllowWriteStreamBuffering = false;
relayRequest.AllowReadStreamBuffering = false;
relayRequest.SendChunked = true;
relayRequest.ContentType = "application/octet-stream";
var stream = relayRequest.GetRequestStream();
string nextLine;
int totalBytes = 0;
// Read a series of lines from the console and transmit them to the server.
while(!string.IsNullOrEmpty((nextLine = Console.ReadLine())))
{
var bytes = Encoding.UTF8.GetBytes(nextLine);
totalBytes += bytes.Length;
Console.WriteLine(
"CLIENT: Sending {0} bytes ({1} total)",
bytes.Length,
totalBytes);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
var response = relayRequest.GetResponse();
Console.WriteLine(response);
}
理由
我的具体动机是为 RTP 客户端编写 HTTPS 隧道。但是,这个问题在即时消息聊天应用程序的上下文中也是有意义的。您不希望部分聊天消息通过,然后必须等待消息 2 找出消息 1 的结尾......!
【问题讨论】:
-
我想这是在应用层之下处理的,在 http.sys 的某个地方。您的网络服务器(可能)连接了 http.sys 提供的 http 管道。我将关注一个有趣的问题,但我的直觉是,您需要切换到 Socket 才能对请求数据进行这种查看。
-
@spender 我不这么认为——分块发生在 HTTP 层,所以理论上没有理由 HttpRequestStream 类(这是 WebAPI 用来读取流的类)不能'不检测分块消息边界并在该点返回。分块消息边界只是一个数字(说明后面有多少字节),然后是 CRLF,然后是字节,然后是另一个 CRLF。
-
如果您使用的是 HttpListener,您最好阅读以下内容:"The HTTP Server API decodes chunked messages on the receive side, but does not perform chunked encoding on the send side." 除非我误解了这意味着什么,很明显您不会看到因为 .Net 使用的 API 甚至在它到达你的应用程序之前就已经完成了。
-
您可能有兴趣查看 nowin 项目,但您可能仍然需要花点时间才能获得这么低的堆栈。
-
@spender 有趣的链接,但有点混乱。如果我没看错,它说明它将解码一个分块的请求,但不会在响应中编码成块。这是我看到的行为 - WebAPI 确实 解码请求中的块(从某种意义上说,我得到了客户端发送的字节,而不是块编码的字节)。但是,我希望请求流在到达块边界时从读取中返回。想一想,我才意识到这太晚了——请求流是后解码的,所以不知道分块。
标签: c# http asp.net-web-api2 owin