ocamlmultiplayerlwt

Ocaml Lwt - some implementations of multiplayer game


I'm going on to writing a simple implementation of tic-tac-toe server (via telnet). The task - players connect to server and after they send START the server looks for a partner who typed START too, and game begins. A piece of code:

let handle_income () =
        let con = Lwt_unix.accept sock in 
        con >>= fun (cli, addr) ->
        let player = Lwt.return {state = Sleeping; descriptor = Lwt.return cli} in
        send_to_client player "Welcome to the server. To start game type in START and press Enter";
        player;;

let rec make_ready player = 
        player >>= fun {state; descriptor} ->
            send_to_client player "Waiting for start command";
            let answer = read_from_client player in 
                answer >>= fun str ->
                match str with
                    |"Start" -> 
                        let ready_client =  Lwt.return { state = Ready; descriptor = descriptor} in 
                        ready_client
                    | _ -> 
                        send_to_client player "Unknown command. try again";
                        make_ready player;;

I'm completely new to Ocaml (Lwt especially). So, will you be so kind as to give to me a piece of advice how to make players' START to look for another player? Should I use list with all-time iteration checking players state, high-level functions which waits for the second player typed START(I'm not sure it's possible), Lwt wakers, Lwt broadcast, creating another a' Lwt wich is Sleep until has 2 Lwt.t players or something? I don't know how to implement that the cleverest way. Thank you much.


Solution

  • One possibility:

    Have the connect function put each new connection in a Lwt_mvar.

    Have a Lwt.async thread that loops. On each iteration take two connections from the mvar and spawn a game between them.