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

标签 c# http tcp stream

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/

相关文章:

node.js - 如何使用node.js和http下载文件?

java - 是否有适用于 Java 的 HttpCahce 客户端库?

c# - 动态加载html代码

c# - 如何使用嵌入式 View 模型

php - 发送文件 POST C++

Java Sockets TCP 发送和接收

Swift:未声明的类型 TCPClient

c# - 通过 Internet 问题设置 TCP/IP 连接

c# - CaSTLe Windsor "Container"和 "Kernel"有什么区别?

c# - 使用包含对自身引用的 OData 对象创建表时出现 SQLite 异常