dream/example/k-websocket
Anton Bachin c5514d72e3 Use esy
2021-04-21 10:49:15 +03:00
..
2021-04-07 17:18:38 +03:00
2021-03-25 01:59:19 +03:00
2021-04-21 10:49:15 +03:00
2021-04-21 10:49:15 +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://localhost:8080/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 "Good-bye!" websocket in
            Dream.close_websocket websocket
          | _ ->
            Dream.close_websocket websocket));

  ]
  @@ Dream.not_found
$ npm install esy && npx esy
$ npx esy start

Visit http://localhost:8080 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