Skip to content

Instantly share code, notes, and snippets.

@1hko
Created May 18, 2018 20:42
Show Gist options
  • Save 1hko/324dc31cb4ee3242be36aa9e5a69f0bd to your computer and use it in GitHub Desktop.
Save 1hko/324dc31cb4ee3242be36aa9e5a69f0bd to your computer and use it in GitHub Desktop.
open Core
open Async
(* Copy data from the reader to the writer, using the provided buffer
as scratch space *)
let rec copy_blocks buffer r w =
Reader.read r buffer
>>= function
| `Eof -> return ()
| `Ok bytes_read ->
Writer.write w (Bytes.to_string buffer) ~len:bytes_read;
Writer.flushed w
>>= fun () ->
copy_blocks buffer r w
(* part 1 *)
(** Starts a TCP server, which listens on the specified port, invoking
copy_blocks every time a client connects. *)
let run () =
let host_and_port =
Tcp.Server.create
~on_handler_error:`Raise
(Tcp.Where_to_listen.of_port 8765)
(fun _addr r w ->
let buffer = Bytes.create (16 * 1024) in
copy_blocks buffer r w)
in
ignore (host_and_port : (Socket.Address.Inet.t, int) Tcp.Server.t Deferred.t)
(* part 2 *)
(* Call [run], and then start the scheduler *)
let () =
run ();
never_returns (Scheduler.go ())
@1hko
Copy link
Author

1hko commented May 18, 2018

The async docs landing page instructs, "Read more in Chapter 18 of Real World OCaml," perhaps suggesting the book should be used as a reference. This is potential point of frustration for many readers of the book as the code examples in the book will not run and it's not clear how to diagnose the issue.

@1hko
Copy link
Author

1hko commented May 18, 2018

I just found Real World OCaml v2. I see the updated echo server example has the same changes as above 🏆

So I guess I've been reading the wrong version of the book! I'll read through v2 and who knows, maybe I'll be able to help find some fixes later on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment