Working with ocaml Lwt sockets

微笑、不失礼 提交于 2019-12-04 21:12:22

A value of type 'a Lwt.t represents a thread that will evaluate to a value of type 'a once it is ready (or to an error is something went wrong). The only way to get 'a from 'a Lwt.t is to bind it to another function, that will be called as soon, as 'a Lwt.t thread is finished and data is ready. You can bind with Lwt.bind function, also available in an infix notation >>=.

For example:

let process_client fd = 
  Lwt_unix.accept fd >>= fun (cli,sock) ->
  let chan = Lwt_io.(of_fd ~mode:output cli) in
  Lwt_io.fprintf chan "hi there, and bye!" >>= fun () ->
  Lwt_io.close chan

This uses infix notation, you can rewrite it more verbose:

let reply chan = 
  Lwt_io.fprintf chan "hi there, and bye!"

let finish chan = Lwt_io.close chan

let create_chan = Lwt_io.(of_fd ~mode:output cli)

let process_client fd = 
  let accept_t = Lwt_unix.accept fd in
  let chan_t = Lwt.map accept_t create_chan in
  let reply_t = Lwt.bind accept_t reply in 
  Lwt.bind reply_t finish

Where _t designates thread. I.e., accept_t is a thread that will eventually return a pair of a file descriptor and a socket address. chan_t is a thread that will return a channel (for doing buffered io).

Lwt also comes with a support for special syntax. Actually with support for two syntaxes, the old with camlp4 and a newer one with ppx. In old syntax, one can write the process_client function as follows:

let process_client fd = 
  lwt (cli,sock) = Lwt_unix.accept fd in
  let chan = Lwt_io.(of_fd ~mode:output cli) in
  lwt () = Lwt_io.fprintf chan "hi there, and bye!" in
  Lwt_io.close chan

There lwt is a special form of let that not only binds names to values, but also waits for them to evaluate.

I hope that I answered all your questions. You may also find this library interesting.

P.S. I didn't test the code, so if you have any issues, don't hesitate to ask.

P.P.S. I left a proper shutdown procedure, to keep code simple.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!