【发布时间】:2017-04-08 14:59:51
【问题描述】:
我正在尝试使用 TcpClient 使用 HTTP 协议发送数据。但我在这里遇到了一个问题。我发送的数据(在标头之后)没有完全发送到客户端的应用程序(例如浏览器)。代码:
// Building data.
string notfound = "NOT FOUND";
byte[] data = Encoding.UTF8.GetBytes(notfound);
// Building header.
m_responseBuilder.Append("HTTP/1.1 404 Not Found").Append(CRLF);
m_responseBuilder.Append("Server: ETP").Append(CRLF);
m_responseBuilder.Append("Content-Type: text/plain").Append(CRLF);
m_responseBuilder.Append("Content-Length: ").Append(data.Length.ToString()).Append(CRLF);
m_responseBuilder.Append(CRLF);
byte[] header = Encoding.UTF8.GetBytes(m_responseBuilder.ToString());
// Sending header.
await SendDataAsync(header);
// Sending data.
await SendDataAsync(data);
SendDataAsync:
async Task SendDataAsync(byte[] data)
{
try
{
await m_tcpchannel.WriteAsync(data, 0, data.Length);
}
catch
{
DestroyConnection();
}
}
我得到了什么:
NOT FOUN
这里怎么了?
【问题讨论】:
-
1) 为什么不使用 HttpListener? 2)当然它坏了,你把手指伸进字节汤里搅拌。 (您不能对图像进行 UTF8 编码;编码是针对字符串的,这就是它在 System.Text 命名空间中的原因)。
-
1) 我想学习abt http包
-
2) 文件未编码为字符串,直接以字节形式发送
-
SendResponse() 不编码任何东西。它是作为字节发送的
-
啊。我的错。