我正在编写一个极小的Web服务器,用于教育目的。
对于以下代码,如果我请求包含图像的HTML页面,则无法在浏览器中看到该图像。我做错了什么?
static void Main(string[] args)
{
TcpListener listener = new TcpListener(9999);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
string request = GetRequest(client.GetStream(),
client.ReceiveBufferSize);
WriteOutput(request, client.GetStream());
client.Close();
}
}
static void WriteOutput(string request, NetworkStream output)
{
try
{
string[] reqs = request.Split(' ');
WriteOutputHelper(output, reqs[1].Substring(1));
}
catch (Exception)
{
WriteOutputHelper(output, "404.html");
}
}
private static void WriteOutputHelper(NetworkStream output, string file)
{
byte[] statusLine = (new System.Text.ASCIIEncoding()).
GetBytes(GetStatusLine(file) + "\r\n\r\n");
output.Write(statusLine, 0, statusLine.Length);
byte[] ContentType =
(new System.Text.ASCIIEncoding()).GetBytes(GetContentType(file) +
"\r\n\r\n");
output.Write(ContentType, 0, ContentType.Length);
byte[] response = System.IO.File.ReadAllBytes("C:\\" + file);
output.Write(response, 0, response.Length);
output.Flush();
}
static string GetContentType(string fileName)
{
string i = "<META http-equiv=\"Content-Type\" content=\"";
if ((fileName.IndexOf(".htm") > -1) || (fileName.IndexOf(".html") > -1))
i = i + "text/html";
else if (fileName.IndexOf(".jpg") > -1)
i = i + "image/jpeg";
i = i + ";\">";
return i;
}
static string GetStatusLine(string fileName)
{
string i = "HTTP/1.0 ";
if (fileName.IndexOf("404") > -1)
return i + "404 Not Found";
else if (fileName.IndexOf("jpg") > -1)
return i + "302 Found";
return i + "200 OK";
}
static string GetRequest(NetworkStream reqStream,int bufSize)
{
byte[] bytesFrom = new byte[10025];
reqStream.Read(bytesFrom, 0, bufSize);
string request = System.Text.Encoding.ASCII.GetString(bytesFrom);
return request;
}
抱歉,我没有看到需要翻译的内容。请您重新发送一遍。
static void imageTest(NetworkStream output)
{
byte[] fileContent = System.IO.File.ReadAllBytes("C:\\sachin.jpg");
string statusLine = "HTTP/1.0 200 OK" + System.Environment.NewLine;
string contentType = "Content-type: image/jpeg" + System.Environment.NewLine;
string contentLength = "Content-length: " + fileContent.Length + System.Environment.NewLine;
System.Text.UnicodeEncoding coding = new UnicodeEncoding();
byte[] headers = coding.GetBytes(statusLine + contentType + contentLength);
output.Write(headers, 0, headers.Length);
output.Write(fileContent, 0, fileContent.Length);
output.Flush();
}
对于上面的代码,我在Fiddler中遇到了以下错误。
服务器未返回正确格式的HTTP标头。HTTP标头应以CRLFCRLF结尾,但这些标头以LFLF结尾。
我正在使用Unicode编码,因为我想将字符串转换为字节,并且我只知道使用编码。