0

I am creating a chat server in the Ocaml language using lwt. What I want it to be able to do is prompt the user to enter a nickname, store the nickname, and then output that the user has joined the chat.

I have already tried implementing my own code, as shown below.

let sessions = ref [("",Lwt_io.null)]

(*  + obtain initial nick(name),
    + add (nick,outp) to !sessions, and
    + announce join to other users *)
let handle_login nr (inp,outp) =
  Lwt_io.printl "Enter initial nick:" >>= (* Print a welcome message to outp *)
  fun () -> Lwt_io.read_line inp >>= (* Read the user's nick from inp *)
  fun s -> Lwt.return (nr := s); (* Assign the new value to nr *)
  sessions := List.concat nr (* Adds nr to sessions *)
  send_all nr "<joined>" >>= (* Inform the other users that the user joined *)
  fun () -> Lwt.return ()

let rec send_all sender msg = Lwt.return ()

let chat_server _ (inp,outp) =
  let nick = ref "" in
  let _ = handle_login nick in (* Calls handle_login with nick *)
  let rec main_loop () =
      Lwt_io.read_line inp >>= handle_input nick outp >>= main_loop in
  Lwt.catch main_loop (fun e -> handle_error e !nick inp outp)
open Lwt.Infix

let port = if Array.length Sys.argv > 1 then int_of_string (Sys.argv.(1)) else 16384
let s = Lwt_io.establish_server_with_client_address (Unix.ADDR_INET(Unix.inet_addr_any, port)) ChatServer.chat_server
let _ = Lwt_main.run (fst (Lwt.wait ()))
let _ = s >>= Lwt_io.shutdown_server (* never executes; you might want to use it in utop, though *)

The result should be that when running the program, it will:

  • print a welcome message to outp,
  • read the nick from inp,
  • assign the new value to nr
  • Add nr to sessions
  • Announce that the user has joined.

Right now, it compiles, but does not output anything.

  • 1
    Hello Caleb and welcome to SO! Your code doesn't show a call to the `chat_server` function. Is it something you forgot to insert in your code (I do that all the time) or something you forgot to mention in your post? – PatJ Apr 16 '19 at 22:16
  • Added. Thanks for the suggestion! – Caleb Twiggs Apr 17 '19 at 17:15
  • HMMMMM this looks a lot like 2041 if I don't say so myself. – widavies Apr 23 '19 at 01:56

0 Answers0