使用Chunked Transfer Encoding将数据发送到客户端

时间:2011-08-19 15:25:21

标签: c# http chunked transfer-encoding

我正在为家庭作业练习构建流式视频服务器,现在我想使用Chunked Transfer Encoding将数据发送到客户端。这是我的代码:

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);

请告诉我使用Chunked Transfer Encoding向客户端发送数据的正确方法。我很感激。

1 个答案:

答案 0 :(得分:0)

我认为你编码分块长度的方法是错误的。在分块传输编码中,每个块的长度也应编码为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");