【问题标题】:Send data to client using Chunked Transfer Encoding使用分块传输编码向客户端发送数据
【发布时间】:2011-08-19 15:25:20
【问题描述】:

我正在为家庭作业构建一个流式视频服务器,现在我想使用分块传输编码向客户端发送数据。这是我的代码:

string statusLine = "HTTP/1.1 200 OK\r\n";
string server = "Server: Cougar/12.0.7600.16385\r\n";
string cacheControl = "Cache-Control: no-cache\r\n";
string desRespPragma1 = "Pragma: no-cache\r\n";
string desRespPragma3 = "Pragma: client-id=" + clientId + "\r\n";
string desRespPragma4 = "Pragma: features=" + "\"" + "seekable,stridable" + "\"" + "\r\n";
string transferEncoding = "Transfer-Encoding: chunked\r\n\r\n";
string desResp = statusLine + server + cacheControl + desRespPragma1 + desRespPragma3+ desRespPragma4 + transferEncoding;

byte [] status = Encoding.ASCII.GetBytes(desResp);
SendData(status);//In SendData function, I’m using NetworkStream to send data

//Send chunked size with CRLN
string CRLF = "\r\n";
byte[] crlf = Encoding.ASCII.GetBytes(CRLF);
byte[] chunkedSize = new byte[3];
chunkedSize[0] = 0x4;
Array.Copy(crlf, 0, chunkedSize, 1, 2);
SendData(chunkedSize); 

//Send data
SendData(tHeader);//tHeader’s byte array, length is 4
//Send \r\n to delimeter
SendData(crlf);

//Send chunked size is 0 with \r\n\r\n to end.
byte[] end = new byte[5];
end[0] = 0;
Array.Copy(crlf, 0, end, 1, 2);
Array.Copy(crlf, 0, end, 3, 2);
SendData(end);

但是客户端没有收到真实的数据。我使用 Wireshark 捕获数据包,我看到客户端收到 2 个分块编码:

HTTP chunked response

End of chunked encoding
            Chunk size: 0 octets
            Chunk boundary
End of chunked encoding
            Chunk size: 0 octets
            Chunk boundary

我正在使用 TcpListener 来监听来自客户端的连接:

TcpListener listener = new TcpListener(ipe);//ipe has my computer ip address and port's 80
Socket socket = listener.AcceptSocket();
NetworkStream ns = new NetworkStream(socket);

请告诉我使用分块传输编码向客户端发送数据的正确方法。我很感激。

【问题讨论】:

  • 你没有写任何关于 http impelementation 的东西......它是你自己的(每个 TcpListener)吗?它是每个 HttpListener 内置的吗?还是通过 IIS HttpHandler/HttpModule ?
  • @Yahia:我正在使用 TcpListener 来监听来自客户端的连接
  • 你为什么使用 TcpListener ? HttpListener 使用类似于 IIS 的一个名为 HTTP.SYS 的内核模块,并且性能非常好,并且它具有适用于 HTTP 的工作实现,包括 Chunked 和许多其他东西......
  • 我知道。但在我的练习中,我必须使用 TcpListener。这是我老师的要求。
  • 好的 - 但后来我出去了...希望其他人可以提供帮助...

标签: c# http chunked transfer-encoding


【解决方案1】:

我认为您对分块块长度进行编码的方式是错误的。在分块传输编码中,每个块的长度也应该编码为 ASCII 字符串,例如:

    byte[] chunkedSize = System.Text.Encoding.ASCII.GetBytes("4\r\n\r\n");
    byte[] end = System.Text.Encoding.ASCII.GetBytes("0\r\n\r\n");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2013-02-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多