mirror of
https://github.com/aantron/dream.git
synced 2025-11-09 00:13:46 -05: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!
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:
l-httpsenables HTTPS.
