Created
May 18, 2018 20:42
-
-
Save 1hko/324dc31cb4ee3242be36aa9e5a69f0bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.