Advertisement
Guest User

Untitled

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