-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.ml
More file actions
49 lines (39 loc) · 1.42 KB
/
socket.ml
File metadata and controls
49 lines (39 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
module type SocketSig = sig
val make_socket : int -> Unix.file_descr
val listen : Unix.file_descr -> int -> unit
val accept_connection : Unix.file_descr -> Unix.file_descr
val make_connection : Unix.file_descr -> int -> unit
val inchan : Unix.file_descr -> in_channel
val outchan : Unix.file_descr -> out_channel
val write : out_channel -> string -> unit
val read : in_channel -> string
val close : Unix.file_descr -> unit
end
module Socket = struct
(** [get_my_addr ()] returns the address of the current host *)
let get_addr () =
(Unix.gethostbyname (Unix.gethostname ())).h_addr_list.(0)
let make_socket port =
(* Create socket *)
let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
(* Bind the address of the host to the socket *)
Unix.bind sock (Unix.ADDR_INET ((get_addr ()), port));
sock
let listen sock n =
Unix.listen sock n
let accept_connection sock =
(* Make the socket ready to accept connections *)
match Unix.accept sock with
| (s, _) -> s
let make_connection sock port =
(* Attempt to connect with the socket at port *)
Unix.connect sock (Unix.ADDR_INET ((get_addr ()), port))
let inchan sock = Unix.in_channel_of_descr sock
let outchan sock = Unix.out_channel_of_descr sock
let write outchan str =
output_string outchan (str ^ "\n"); flush outchan
let read inchan =
input_line inchan
let close sock =
Unix.close sock
end