开发者

Send data to client using Chunked Transfer Encoding

I’m building a Streaming Video Server for a homework exercise, now I want to send data to client using Chunked Tran开发者_StackOverflow社区sfer Encoding. This is my code :

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

But client don’t receive true data. I use Wireshark to capture packet and I see client receives 2 end of chunked encoding :

HTTP chunked response

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

I'm using TcpListener to listen connection from client :

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

Please show me the correct way to send data to client using Chunked Transfer Encoding. I appreciate it.


I think that your way to encode the chunked block length is wrong. In chunked transfer encoding, each block's length should also be encoded to ASCII strings, like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜