zaach (owner)

Fork Of

Revisions

gist: 221544 Download_button fork
public
Public Clone URL: git://gist.github.com/221544.git
Embed All Files: show embed
OCaml #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
(* 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