OSDN Git Service

implement socket
authormzp <mzpppp@gmail.com>
Tue, 16 Feb 2010 07:30:19 +0000 (16:30 +0900)
committermzp <mzpppp@gmail.com>
Tue, 16 Feb 2010 07:30:19 +0000 (16:30 +0900)
debugger/OMakefile
debugger/socket.ml
debugger/socket.mli
debugger/socketTest.ml [new file with mode: 0644]

index 784fb9a..d047fc5 100644 (file)
@@ -19,6 +19,7 @@ OCAMLOPTLINK= ocamlopt
 .DEFAULT: $(MyOCamlPackage $(PROGRAM), $(FILES))
 
 # test
+OUnitTest(socket, socket)
 
 # phony
 .PHONY: clean
index 9d4f646..9883dfd 100644 (file)
@@ -1,4 +1,23 @@
-type t = int
-let connect _ = assert false
-let send _ = assert false
-let recv _ = assert false
+open Base
+
+type t = in_channel * out_channel
+
+let connect host port =
+  let inet =
+    Unix.inet_addr_of_string host in
+  let addr =
+    Unix.ADDR_INET (inet, port) in
+    Unix.open_connection addr
+
+let close (ic, _) =
+  Unix.shutdown_connection ic
+
+let send (_, oc) s =
+  output_string oc s
+
+let recv (ic, _) len =
+  let buffer =
+    String.make len ' ' in
+  let n =
+    Unix.recv (Unix.descr_of_in_channel ic) buffer 0 len [] in
+    String.sub buffer 0 n
index 6eb148b..c8b9abf 100644 (file)
@@ -1,4 +1,5 @@
 type t
 val connect : string -> int -> t
+val close : t -> unit
 val send : t -> string -> unit
 val recv : t -> int -> string
diff --git a/debugger/socketTest.ml b/debugger/socketTest.ml
new file mode 100644 (file)
index 0000000..dbc0dc7
--- /dev/null
@@ -0,0 +1,45 @@
+open Base
+open OUnit
+
+(* stub server *)
+let server port f =
+  if Unix.fork () = 0 then
+    let sa =
+      Unix.ADDR_INET (Unix.inet_addr_any, port) in
+      Unix.establish_server f sa
+
+let last_msg = ref ""
+
+let send_test port f =
+  server port begin fun ic _ ->
+    try f () with _ -> ();
+    last_msg := input_line ic;
+    Unix.shutdown_connection ic
+  end
+
+let recv_test port f =
+  server port begin fun ic oc ->
+    output_string oc "hi!";
+    try f () with _ -> ();
+    Unix.shutdown_connection ic
+  end
+
+let _ = begin "socket.ml" >::: [
+  "send" >:: begin fun () ->
+    send_test 9000 begin fun () ->
+      let socket =
+       Socket.connect "localhost" 9000 in
+       Socket.send socket "hi";
+       assert_equal "hi" !last_msg;
+       Socket.close socket
+    end;
+  end;
+  "recv" >:: begin fun () ->
+    recv_test 9001 begin fun () ->
+      let socket =
+       Socket.connect "localhost" 9001 in
+       assert_equal "hi!" @@ Socket.recv socket 3;
+       Socket.close socket
+    end;
+  end;
+] end +> run_test_tt_main