Advertisement
Guest User

Client/server communication over unix domain sockets - Ocaml

a guest
Jan 1st, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.82 KB | None | 0 0
  1. (* ocamlfind ocamlc unixsocket.ml -package unix -linkpkg && ./a.out *)
  2. (* Example of 2 ocaml programs communicating over a UNIX socket. *)
  3.  
  4. let socket_file = "domotique.sock";;
  5.  
  6. (* Remove the file if it already existed. *)
  7. try Unix.unlink socket_file with Unix.Unix_error _ -> ();;
  8.  
  9. module Server() = struct
  10.   let socket = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0;;
  11.  
  12.   (* Remove the file after it was created. *)
  13.   Pervasives.at_exit (fun () ->
  14.     Unix.unlink socket_file
  15.   );;
  16.  
  17.   Unix.bind socket (Unix.ADDR_UNIX socket_file);;
  18.   Unix.listen socket 1;;
  19.  
  20.   Printf.printf "After listen \n%!";;
  21.  
  22.   let client_sock, _ = Unix.accept socket;;
  23.  
  24.   (* We assume that we only have a single client for now. *)
  25.  
  26.   Printf.printf "Client found \n%!";;
  27.  
  28.   let in_chan = Unix.in_channel_of_descr client_sock;;
  29.   let out_chan = Unix.out_channel_of_descr client_sock;;  
  30.   let res:string = Marshal.from_channel in_chan;;
  31.   Printf.printf "Client send: %s\n%!" res;;
  32.  
  33.  
  34.   Marshal.to_channel out_chan "Hello, client!" [];;
  35.   Pervasives.flush out_chan;  
  36.  
  37. end
  38.  
  39. module Client()= struct
  40.  
  41.     Unix.sleep 1;;                (* Wait for the server to create the socket. *)
  42.  
  43.   (* Low-level version. *)
  44.   let socket = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0;;
  45.   Unix.connect socket (Unix.ADDR_UNIX socket_file);;
  46.   let in_chan = Unix.in_channel_of_descr socket;;
  47.   let out_chan = Unix.out_channel_of_descr socket;;  
  48.  
  49.   (* High-level version. *)
  50.   (* let in_chan,out_chan = Unix.open_connection (Unix.ADDR_UNIX socket_file);; *)
  51.  
  52.   Marshal.to_channel out_chan "Hello, server!" [];;
  53.   Pervasives.flush out_chan;
  54.   let result = Marshal.from_channel in_chan in
  55.   Printf.printf "Server answered: %s\n%!" result;;
  56.  
  57. end;;
  58.  
  59. match Unix.fork() with
  60. | 0 -> let module C = Client() in ()  
  61. | _ -> let module S = Server() in ()
  62. ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement