gpt4 book ai didi

C# 简单 HTTP 服务器不向浏览器发送响应

转载 作者:可可西里 更新时间:2023-11-01 02:48:42 24 4
gpt4 key购买 nike

System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 8080);
server.Start();
Console.WriteLine("Servidor TCP iniciado");
Console.WriteLine("Aguardando conexao de um cliente...");
TcpClient client = server.AcceptTcpClient();

Console.WriteLine("Um cliente conectou-se ao servidor");

System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
writer.Write("HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n");
writer.Flush();


Console.WriteLine("Desligando servidor");
server.Stop();
Console.ReadKey();

当我打开浏览器并尝试访问 URL http://localhost:8080 时我收到了 ERR_CONNECTION_RESET 错误。我做错了什么?

最佳答案

问题是您有一个不正确的 HTTP 数据包,它不包含 Content-Length,因此浏览器不知道要读取什么。试试下面的代码:

TcpListener server = new TcpListener(System.Net.IPAddress.Loopback, 8080);
server.Start();
Console.WriteLine("Wait for clients");
TcpClient client = server.AcceptTcpClient();

Console.WriteLine("Writing content");
string content = "Goodbye World!";

System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/plain; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: "+ content.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(content);
writer.Flush();

Console.WriteLine("Disconnecting");
client.Close();
server.Stop();
Console.ReadKey();

关于C# 简单 HTTP 服务器不向浏览器发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32646868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com