Skip to content

Instantly share code, notes, and snippets.

@teeler
Created October 8, 2009 20:50
Show Gist options
  • Save teeler/205407 to your computer and use it in GitHub Desktop.
Save teeler/205407 to your computer and use it in GitHub Desktop.
(* a simple echo server in ocaml
* -----------------------------
* uses a high level networking function, similar to SocketServer
* in python, called 'establish_server', see here:
* http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html#VALestablish_server
*)
(*
our echo function
in -> out -> unit
*)
let echo ic oc =let echo ic oc =
let c = ref true in
while !c do
let pid = Unix.getpid () in
let msg = Printf.sprintf "[%d] echo> " pid in
output oc msg 0 (String.length msg);
flush oc;
let l = try input_line ic with End_of_file -> c := false; "" in
let resp = Printf.sprintf "[%d] echo'd> %s\n" pid l in
output oc resp 0 (String.length resp)
done
(* main *)
let _ =
let addr = Unix.inet_addr_of_string "0.0.0.0" in (* localhost *)
let sa = Unix.ADDR_INET (addr,4242) in
(* (in -> out -> unit) -> sockaddr -> () *)
Unix.establish_server echo sa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment