Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* ocamlfind ocamlc unixsocket.ml -package unix -linkpkg && ./a.out *)
- (* Example of 2 ocaml programs communicating over a UNIX socket. *)
- let socket_file = "domotique.sock";;
- (* Remove the file if it already existed. *)
- try Unix.unlink socket_file with Unix.Unix_error _ -> ();;
- module Server() = struct
- let socket = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0;;
- (* Remove the file after it was created. *)
- Pervasives.at_exit (fun () ->
- Unix.unlink socket_file
- );;
- Unix.bind socket (Unix.ADDR_UNIX socket_file);;
- Unix.listen socket 1;;
- Printf.printf "After listen \n%!";;
- let client_sock, _ = Unix.accept socket;;
- (* We assume that we only have a single client for now. *)
- Printf.printf "Client found \n%!";;
- let in_chan = Unix.in_channel_of_descr client_sock;;
- let out_chan = Unix.out_channel_of_descr client_sock;;
- let res:string = Marshal.from_channel in_chan;;
- Printf.printf "Client send: %s\n%!" res;;
- Marshal.to_channel out_chan "Hello, client!" [];;
- Pervasives.flush out_chan;
- end
- module Client()= struct
- Unix.sleep 1;; (* Wait for the server to create the socket. *)
- (* Low-level version. *)
- let socket = Unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0;;
- Unix.connect socket (Unix.ADDR_UNIX socket_file);;
- let in_chan = Unix.in_channel_of_descr socket;;
- let out_chan = Unix.out_channel_of_descr socket;;
- (* High-level version. *)
- (* let in_chan,out_chan = Unix.open_connection (Unix.ADDR_UNIX socket_file);; *)
- Marshal.to_channel out_chan "Hello, server!" [];;
- Pervasives.flush out_chan;
- let result = Marshal.from_channel in_chan in
- Printf.printf "Server answered: %s\n%!" result;;
- end;;
- match Unix.fork() with
- | 0 -> let module C = Client() in ()
- | _ -> let module S = Server() in ()
- ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement