Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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();
When I open the browser and try to access the URL http://localhost:8080 I get the ERR_CONNECTION_RESET error. What am I doing wrong?
The problem is that you have an incorrect HTTP Packet, it does not contain a Content-Length, so the browser does not know what to read. Try the following code:
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();
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.