dream/example/k-websocket
2021-05-11 07:04:14 +03:00
..
2021-03-25 01:59:19 +03:00
2021-05-03 09:27:44 +03:00
2021-05-02 21:04:53 +03:00

k-websocket


In this example, the client connects to the server by a WebSocket. They then follow a silly protocol: if the client sends "Hello?", the server responds with "Good-bye!". The client displays the message in an alert box:

let home =
  <html>
    <body>
      <script>

      var socket = new WebSocket("ws://" + window.location.host + "/websocket");

      socket.onopen = function () {
        socket.send("Hello?");
      };

      socket.onmessage = function (e) {
        alert(e.data);
      };

      </script>
    </body>
  </html>

let () =
  Dream.run
  @@ Dream.logger
  @@ Dream.router [

    Dream.get "/"
      (fun _ ->
        Dream.html home);

    Dream.get "/websocket"
      (fun _ ->
        Dream.websocket (fun websocket ->
          match%lwt Dream.receive websocket with
          | Some "Hello?" ->
            let%lwt () = Dream.send websocket "Good-bye!" in
            Dream.close_websocket websocket
          | _ ->
            Dream.close_websocket websocket));

  ]
  @@ Dream.not_found
$ cd example/k-websocket
$ npm install esy && npx esy
$ npx esy start

Visit http://localhost:8080 [playground] to get the whole exchange started!

WebSocket alert


See WebSockets in the API docs.

If you are running under HTTPS, be sure to use wss:// for the protocol scheme, rather than ws://, on the client.


Last step:


Up to the tutorial index