Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2011
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.56 KB | None | 0 0
  1. (*
  2.     compile : ocamlc  -custom -o serv_up unix.cma kot.ml -cclib -lunix
  3.         where kot.ml is this file
  4. *)
  5. open Unix
  6. let establish_server server_fun sockaddr =
  7. let domain = domain_of_sockaddr sockaddr in
  8. let sock = Unix.socket domain Unix.SOCK_STREAM 0
  9. in Unix.bind sock sockaddr ;
  10.   Unix.listen sock 3;
  11.   while true do
  12.     let (s, caller) = Unix.accept sock
  13.     in match Unix.fork() with
  14.         0 -> if Unix.fork() <> 0 then exit 0 ;
  15.           let inchan = Unix.in_channel_of_descr s
  16.           and outchan = Unix.out_channel_of_descr s
  17.           in server_fun inchan outchan ;
  18.             close_in inchan ;
  19.             close_out outchan ;
  20.             exit 0
  21.       | id -> Unix.close s; ignore(Unix.waitpid [] id)
  22.   done
  23. ;;
  24.  
  25. let get_my_addr () =
  26.    (Unix.gethostbyname(Unix.gethostname())).Unix.h_addr_list.(0) ;;
  27.  
  28. let main_server  serv_fun =
  29.    if Array.length Sys.argv < 2 then Printf.eprintf "usage : serv_up port\n"
  30.    else try
  31.           let port =  int_of_string Sys.argv.(1) in
  32.           let my_address = get_my_addr()
  33.           in establish_server serv_fun  (Unix.ADDR_INET(my_address, port))
  34.         with
  35.           Failure("int_of_string") ->
  36.             Printf.eprintf "serv_up : bad port number\n" ;;
  37. let uppercase_service ic oc =
  38.    try while true do    
  39.          let s = input_line ic in
  40.          let r = String.uppercase s
  41.          in output_string oc (r^"\n") ; flush oc
  42.        done
  43.    with _ -> Printf.printf "End of text\n" ; flush oc ; exit 0 ;;
  44.  
  45. let go_uppercase_service () =
  46.    Unix.handle_unix_error main_server uppercase_service ;;
  47.  
  48. let _ = go_uppercase_service ();;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement