<!DOCTYPE HTML>

<html>
<head>
    <title>WS RTT Client</title>
    <script type = "text/javascript">
        let ws;
        let lastPing = 0;
        let lastPong = 0;

        function WebSocketTest() {

            if ("WebSocket" in window) {
                // alert("WebSocket is supported by your Browser!");
                console.log("WebSocket is supported by your Browser!");

                // Let us open a web socket
                // ws = new WebSocket("ws://192.168.0.163:1337/");
                ws = new WebSocket("ws://localhost:1337/");

                ws.onopen = function() {
                    // Web Socket is connected, send data using send()
                    ws.send("BONJOUR");
                    console.log("BONJOUR sent");
                };

                ws.onmessage = function (evt) {
                    const received_msg = evt.data;
                    // alert("Message is received...");
                    console.log("Message received: " + received_msg);
                    if (received_msg === "ping") {
                        ws.send("pong");
                        console.log("responded with pong");
                    } else if (received_msg === "pong") {
                        console.log("pong received");
                        lastPong = performance.now();
                        console.log("lastPong - lastPing = " + (lastPong - lastPing));
                    }
                };

                ws.onclose = function() {
                    // websocket is closed.
                    // alert("Connection is closed...");
                    console.log("Connection closed");
                };

            } else {
                // The browser doesn't support WebSocket
                alert("WebSocket NOT supported by your Browser!");
            }
        }

        function Ping() {
            lastPing = performance.now();
            ws.send("ping");
        }
    </script>

</head>

<body>
    <div id = "sse">
        <a href = "javascript:WebSocketTest()">Run WebSocket</a>
    </div>
    <a href = "javascript:Ping()">Ping</a>
</body>
</html>