I’m playing around with a simple webserver written in F#. As I have noticed, if I hit refresh in Firefox, after some tries, I get an error page saying:
The connection was reset
The connection to the server was reset while the page was loading.
Why does this occur seemingly randomly (increasing the backlog to 1000 didn’t help)? Also, why is Firefox the only browser which displays the response of my webserver? I guess my response is not valid, is that right?
The code of the webserver:
module Program
open System
open System.Net.Sockets
open System.IO
type TcpListener with
member this.AsyncAcceptSocket =
Async.FromBeginEnd(this.BeginAcceptSocket, this.EndAcceptSocket)
type Main =
static member Init () =
let tcpListener = new TcpListener(80)
tcpListener.Start()
let rec loop =
async{
let! socket = tcpListener.AsyncAcceptSocket
Async.Start(loop)
let stream = new NetworkStream(socket)
let streamWriter = new StreamWriter(stream)
streamWriter.WriteLine("HTTP/1.0 200 OK");
streamWriter.WriteLine("Date: Fri, 15 Nov 2011 23:59:59 GMT");
streamWriter.WriteLine("Content-Type: text/html");
streamWriter.WriteLine("Content-Length: 13540");
streamWriter.WriteLine("")
streamWriter.WriteLine("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
streamWriter.WriteLine("<html>");
streamWriter.WriteLine("<body>");
streamWriter.WriteLine("<h1>This is the title</h1>");
streamWriter.WriteLine("</body>");
streamWriter.Write("</html>");
streamWriter.Flush()
stream.Close()
socket.Close()
}
Async.Start(loop)
Console.ReadLine()
Main.Init()
EDIT
It seems the problem isn’t related to the way I invoked loop in the previous solution. I have reduced the program to this (and my problems still persist):
module Program
open System
open System.Net.Sockets
open System.IO
let tcpListener = new TcpListener(80)
tcpListener.Start()
while true do
let socket = tcpListener.AcceptSocket()
let stream = new NetworkStream(socket)
let streamWriter = new StreamWriter(stream)
streamWriter.WriteLine("response");
streamWriter.Flush()
stream.Close()
socket.Close()
Console.ReadLine()
Here’s a working version. I’d use TcpClient instead of socket so you don’t have to manage its underlining stream.