Advanced Functional Prog.


Network Programming

All the classes from .Net are available in F# with for instance System.Net.Socket to make network communications.

The following code illustrates how to query a web page:

let uri    = new Uri("https://afp.laurent-thiry.fr")
let socket = new Socket(SocketType.Stream,ProtocolType.Tcp)
socket.Connect(uri.Host,80)

let send (msg:string) = 
  socket.Send(Encoding.UTF8.GetBytes msg,msg.Length,SocketFlags.None)

let response _ =
  let bytes : byte array = Array.zeroCreate 1024
  let rec loop msg = 
    let count = socket.Receive bytes
    if (count=0) then msg 
      else loop (msg+Encoding.UTF8.GetString(bytes,0,count))
  loop "" 

let http_get doc = 
  send ("GET "+doc+" HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")

let http_body (str:string):string = (str.Split "\r\n\r\n")[1]

http_get "/page/index" |> response |> http_body |> printfn "%s"

As an exercice, try to create a (server) socket that "await" a client connection and "echo" the received message.