创建聊天服务器

时间:2019-04-16 20:57:33

标签: ocaml ocaml-lwt

我正在使用lwt创建Ocaml语言的聊天服务器。我希望它能够执行的操作是提示用户输入一个昵称,存储该昵称,然后输出用户已加入聊天的消息。

我已经尝试实现自己的代码,如下所示。

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 *)

结果应该是,在运行程序时,它将:

  • 将欢迎消息打印出来,
  • 从inp读取缺口,
  • 将新值分配给nr
  • 将nr添加到会话中
  • 宣布用户已加入。

现在,它可以编译,但不输出任何内容。

0 个答案:

没有答案