websocketclient javascript

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>WebSocket Screenshot Viewer</title>

</head>

<body>

    <h1>WebSocket Screenshot Viewer</h1>

    <div id="status">Status: Not connected</div>

    <img id="screenshot" alt="Screenshot will appear here" style="max-width: 100%; margin-top: 20px;">


    <script>

        const serverUrl = "ws://192.168.31.53:12345"; // Update with the correct server URL if needed

        const statusDiv = document.getElementById("status");

        const screenshotImg = document.getElementById("screenshot");


        // Initialize the WebSocket connection

        const socket = new WebSocket(serverUrl);


        // WebSocket event handlers

        socket.onopen = () => {

            console.log("Connected to WebSocket server.");

            statusDiv.textContent = "Status: Connected to server";

            startScreenshotRequests();

        };


        socket.onmessage = (event) => {

            if (event.data instanceof Blob) {

                console.log("Screenshot received.");

                displayScreenshot(event.data);

            } else {

                console.log("Message from server:", event.data);

            }

        };


        socket.onerror = (error) => {

            console.error("WebSocket error:", error);

            statusDiv.textContent = "Status: Error occurred!";

        };


        socket.onclose = () => {

            console.log("WebSocket connection closed.");

            statusDiv.textContent = "Status: Disconnected";

            stopScreenshotRequests();

        };


        let screenshotInterval;


        // Start sending screenshot requests every 300ms

        function startScreenshotRequests() {

            if (!screenshotInterval) {

                screenshotInterval = setInterval(() => {

                    if (socket.readyState === WebSocket.OPEN) {

                        socket.send("GET_SCREENSHOT");

                    }

                }, 300);

            }

        }


        // Stop sending screenshot requests

        function stopScreenshotRequests() {

            if (screenshotInterval) {

                clearInterval(screenshotInterval);

                screenshotInterval = null;

            }

        }


        // Function to display the received screenshot

        function displayScreenshot(blob) {

            const url = URL.createObjectURL(blob);

            screenshotImg.src = url;


            // Clean up the object URL after the image loads

            screenshotImg.onload = () => {

                URL.revokeObjectURL(url);

            };

        }

    </script>

</body>

</html>


Comments

Popular posts from this blog

Lab Network 2024

Submission Lab Java 2024

Tutorial OOP(reversion java)