Advertisement
Guest User

Untitled

a guest
Mar 5th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.99 KB | None | 0 0
  1. module Server
  2.  
  3. [<EntryPoint>]
  4. let main argv =
  5.     let port = 8080
  6.     //Use svarende til C#, kalder dispose ved GB
  7.     use hl = new System.Net.HttpListener ()
  8.     hl.Prefixes.Add <| sprintf "http://+:%d/" port //%d inserts port intro string
  9.     //Starting server
  10.     hl.Start ()
  11.  
  12.     //Server loop for handling requests
  13.     let rec loop ()  =
  14.         let ctx         = hl.GetContext()
  15.         let request     = ctx.Request
  16.         let response    = ctx.Response
  17.         let meth        = request.HttpMethod
  18.         let path        = request.RawUrl
  19.         let rip         = request.RemoteEndPoint.Address
  20.         let rport       = request.RemoteEndPoint.Port
  21.        
  22.         //Waiting for incomming HTTP Requests
  23.         let body =
  24.             use is = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)
  25.             is.ReadToEnd()
  26.  
  27.         //Eg "Create /resorce/C from ::1 57916 [data]"
  28.         printfn "%s %s from %s %d [%s]" meth path (rip.ToString()) rport body
  29.        
  30.         //Function for sending a reply, calls loop recusive
  31.         //Mangler at have en globalstate/store er sendes rundt  
  32.         let reply answer status reason =
  33.             printfn "--> %d %s %s" status reason answer //Prints response to shell
  34.             //Sets responsevalues "imperative"
  35.             response.StatusCode         <- status
  36.             response.StatusDescription  <- reason
  37.             //Transforms answer string -> byte []
  38.             let buffer = System.Text.Encoding.UTF8.GetBytes(answer)
  39.             response.ContentLength64    <-  int64 buffer.Length
  40.             response.OutputStream.Write(buffer, 0, buffer.Length)
  41.             response.OutputStream.Close();  
  42.             loop ()
  43.  
  44.         match meth with
  45.         | "GET"      -> reply "Handling Get" 200 "OK"
  46.         | "PUT"      -> reply "Handling Put" 200 "OK"
  47.         | "DELETE"   -> reply "Handling Delete" 200 "OK"
  48.         | "CREATE"   -> reply "Handling Create" 200 "OK"
  49.  
  50.     //Starting loop
  51.     loop ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement