Quantcast
Channel: OCaml - Topics tagged dune
Viewing all articles
Browse latest Browse all 527

How to send a String to 2 other clients through Lwt and get the answer?

$
0
0

Hello, this will be a big post but its mainly due to the socket code. What i want to know how to do is in the main function. I am trying to create a function called send_msg that will send a question to 2 clients and then another function called getAnswer that will retrieve the answer from the client using the lwt library. I will attach the server code. No matter what i do i can’t get the question to show in my client terminals.

open Base
(* open Lwt *)

type player = {input: Lwt_io.input_channel; output: Lwt_io.output_channel}

let (>>=) = Lwt.(>>=)
let return = Lwt.return


let getPlayers n : player list Lwt.t =
  let sockaddr = Lwt_unix.ADDR_INET (UnixLabels.inet_addr_loopback, 3003) in
  let sock = Lwt_unix.socket Lwt_unix.PF_INET Lwt_unix.SOCK_STREAM 0 in
  Lwt_unix.set_close_on_exec sock ;
  Lwt_unix.setsockopt sock Lwt_unix.SO_REUSEADDR true ;
  Lwt_unix.bind sock sockaddr >>= fun () ->
  Lwt_unix.listen sock 3003 ;
  let rec acceptPlayer n acc : player list Lwt.t =
    if n > 0 then
      let pt =
        Lwt_unix.accept sock >>= fun (cliFD, _sock) ->
        let inputChan = Lwt_io.of_fd ~mode:Lwt_io.input cliFD in
        let outputChan = Lwt_io.of_fd ~mode:Lwt_io.output cliFD in
        {input=inputChan; output= outputChan} |> return
      in
      pt >>= fun p ->
      acceptPlayer (n - 1) (p :: acc)
    else
      acc |> return
  in
  acceptPlayer n []



let closePlayers listPlayers =
  Lwt_list.map_p
    (fun  player -> Lwt_io.close player.input)
    listPlayers
let _ = Lwt_main.run

    (* Creating player )
    (
      (Lwt_io.fprintf Lwt_io.stderr "Waiting for players...\n") >>=
      fun () -> let threadListPlayers = getPlayers 2 in
      ( actions )


      threadListPlayers >>=
      send_msg "Ocaml is cool : True or False??" >>= send_msg:string ->player list -> player list Lwt.t

     ( Default form for send_msg
      *
      * let send_msg (msg : string) (lj : player list) : player list Lwt.t =
      *   Lwt_list.mapp (fun p -> ...fprintf.... p.output.... return...) lj
      )


     ( sendMsg "Ocaml is cool: True or False ??" >>=
      * getAnswer >>=
      * filterWinners "True" >>=
      *
      * sendMsg "Javascript Is nice: True ou False ?" >>=
      * getAnswer >>=
      * filterWinners "True" >>=
      *
      * sendMsg "What do programmers code with : 1) nano, 2) emacs, 3) vi, 4) rainbows ?" >>=
      * filterFastest  >>= 'where' filterFastestCorrect "4" >>=
      * sendMsg  "Nice!" >>= )


     ( Closing player *)
     >>= fun  -> threadListPlayers >>= closePlayers)

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 527

Trending Articles