Source

StarML / main.ml

Full commit

module Bufreader : sig
    type t
    val new_from : Unix.file_descr -> t
    val read_line : t -> string
end = struct
    type t = Unix.file_descr

    let new_from fd = fd

    let read_char fd =
        let buf = String.make 1 ' ' in
        let z = Unix.recv fd buf 0 1 [] in
        assert (z = 1);
        buf.[0]

    let read_line fd =
        let c = ref ' ' in
        let b = Buffer.create 16 in
        while (!c <> '\n') do
            c := read_char fd;
            Buffer.add_char b !c
        done;
        Buffer.contents b

end

let main _ =
    print_endline "Sup dawg, I heard you like starcraft";
    print_endline "------------------------------------";
    print_endline "Waiting...";
    let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
    let saddr = Unix.ADDR_INET (Unix.inet_addr_any, 13337) in
    Unix.bind sock saddr;
    Unix.listen sock 4;
    let buflen = 512 in
    let buf = String.create buflen in
    let (fd, _) = Unix.accept sock in
    print_endline "Got it !";
    let reader = Bufreader.new_from fd in
    while true do
        let line = Bufreader.read_line reader in
        Printf.printf "Recv <%s>\n" line;
        flush stdout;
        begin
            ignore (Unix.send fd "00" 0 2 []);
        end
    done

let _ = main ()