Google PlusFacebook iconTwitter icon+44 113 260 4010 contact@branded3.com

Creating a simple HTTP Server with F#

Following on from Doug’s post about Double Meta Refresh; we found it is quite handy to be able to visually test what the referrer is when visiting a link.

Again, I call on my favourite language – F# – for doing quick scripts and utilities!

open System
open System.Net
open System.Text

let listener (handler:(HttpListenerRequest -> HttpListenerResponse -> Async<unit>)) =
    let hl = new HttpListener()
    hl.Prefixes.Add "http://*:8080/"
    hl.Start()
    let task = Async.FromBeginEnd(hl.BeginGetContext, hl.EndGetContext)
    async {
        while true do
            let! context = task
            Async.Start(handler context.Request context.Response)
    } |> Async.Start

let output (req:HttpListenerRequest) =
    if req.UrlReferrer = null then
        "No referrer!"
    else
        "Referrer: " + req.UrlReferrer.ToString()

listener (fun req resp ->
    async {
        let txt = Encoding.ASCII.GetBytes(output req)
        resp.OutputStream.Write(txt, 0, txt.Length)
        resp.OutputStream.Close()
    })

printfn "Press return to exit..."
Console.ReadLine()
    |> ignore

At the top we have a function called listener which takes in a handler function clearly shown as the type HttpListenerRequest -> HttpListenerResponse -> Async<unit>

If you’ve ever used HttpListener before, then you may recognise the code in the body of the listener function. It sets up then starts the HttpListener and creates an Async task for the HttpListener. Finally, we pass an anonymous function to listener which simply writes to the response output stream with the text from the output function just above it.

The last few lines are required only if you compile the code. It simply ensures the console application does not exit immediately; if you’re pasting this example into F# Interactive, you can skip them.

Read more posts about F#:

BY Julian Kay AT 8:59am ON Wednesday, 20 April 2011

Our Senior Application Developer, Jules has been immersed in the software development industry for 12 years; revolutionising Branded3’s development process’s for almost three of those years. As well as being our server and mobile development expert; Jules surrounds himself with all things Microsoft and Windows. This isn’t just his job, this is his passion. Follow @juliankay on Twitter

Comments

Comments are closed.