(* Communication routines of the server *) (* #load "unix.cma";; #load "config.cmo";; *) open Config;; open Unix;; (* Show the socket address *) let string_of_sockaddr = function | ADDR_UNIX str -> str | ADDR_INET (inet,port) -> string_of_inet_addr inet ^ ":" ^ string_of_int port ;; (* Clear the address *) let clear_sockaddr = function | ADDR_UNIX str -> (try Sys.remove str with _ -> ()) | ADDR_INET (inet,port) -> () ;; let flush_out () = flush Pervasives.stdout (* Start up the server *) let start_server executor = let () = clear_sockaddr chr_connection in let sock = socket (domain_of_sockaddr chr_connection) SOCK_STREAM 0 in let () = setsockopt sock SO_REUSEADDR true in let () = bind sock chr_connection in let () = listen sock 5 in Printf.printf "Chourai server started %s\n" (string_of_sockaddr chr_connection); flush_out (); let rec loop sock = let (fd,cl_addr) = accept sock in let _ = Printf.printf "New connection from %s\n" (string_of_sockaddr cl_addr); flush_out () in begin try let cin = Unix.in_channel_of_descr fd in let cout = Unix.out_channel_of_descr fd in executor cin cout with e -> Printf.printf "Exception: %s" (Printexc.to_string e); flush_out () end; flush_out (); Unix.close fd; loop sock in loop sock ;;