<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
    body{
        background-color:darkgray;
    }
</style>
<body>
    <div id="main" style="visibility:hidden;margin-left:40%">
        <form onsubmit="return false;">
            <p>
                <span id="nameData"></span>
                <button id="close" style="height:21px;visibility:hidden" onclick="c()">断开连接</button>
            </p>
            <textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
            <br>
            <input type="text" name="message" style="width: 300px">
            <input type="button" value="发送消息" onclick="send(this.form.message.value)">
            <input type="button" onclick="javascript:document.getElementById('responseText').value=''"
                   value="清空聊天记录">
        </form>
        <br>
        <br>
    </div>
    <div id="file">
        <input type='file' id="fileInput" />
        <input type="button" value="发送文件" onclick="sendFile()" />
    </div>
    <div id="register" style="width:300px;height:300px;margin-left:45%">
        <input id="name" type="text" placeholder="请输入你在聊天中的名字" />
        <button id="login" style="height:21px" onclick="A()">连接到服务器</button>

    </div>


    <script type="text/javascript">
        let ip;

        // 获取ip
        function getIpClient() {
            axios.get('https://api.ipify.org?format=json')
                .then(response => {
                    ip = response.data.ip;
                    console.log(ip);
                    // 在这里进行后续操作
                    return ip;
                })
                .catch(error => {
                    console.error(error);
                });
        }
        console.log(ip);

        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        function A() {
            name = document.getElementById("name").value;
            console.log(name);
            if (name != "") {
                if (window.WebSocket) {
                    var nameData = document.getElementById("nameData");
                    nameData.innerHTML += "当前用户："+name;
                    document.getElementById("name").style.visibility = "hidden"
                    document.getElementById("login").style.visibility = "hidden"
                    document.getElementById("close").style.visibility = "visible"
                    document.getElementById("main").style.visibility = "visible"
                    getIpClient(); // 调用获取 IP 地址的函数
                    socket = new WebSocket("ws://38.46.30.148:3000");

                    socket.onmessage = function (event) {
                        var ta = document.getElementById('responseText');
                        ta.value = ta.value + '\n' + event.data
                    };
                    socket.onopen = function (event) {
                        var ta = document.getElementById('responseText');
                        ta.value = "连接开启!";
                    };
                    socket.onclose = function (event) {
                        var ta = document.getElementById('responseText');
                        ta.value = ta.value + "连接被关闭";
                    };
                } else {
                    alert("你的浏览器不支持 WebSocket！");
                }
            } else
                alert("请实名！");
        }
        function send(message) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                if (ip === undefined) {
                    ip = "未知地区";
                } else
                    socket.send("from " + ip + "的" + name + "：" + message);
            } else {
                alert("连接没有开启.");
            }
        }
        function c() {
            socket.close();
            $("#name").attr("readOnly", "true");
            document.getElementById("main").style.visibility = "hidden"
            document.getElementById("name").style.visibility = "visible"
            document.getElementById("login").style.visibility = "visible"
            document.getElementById("close").style.visibility = "hidden"
        }

        function sendFile() {
            var fileInput = document.getElementById('fileInput');
            var file = fileInput.files[0]; // Get the first file from the input

            if (file) {
                var reader = new FileReader();

                // When the file is read it triggers the onload event above.
                reader.onload = function (event) {
                    var arrayBuffer = event.target.result;

                    // Check the WebSocket connection status
                    if (socket.readyState == WebSocket.OPEN) {
                        socket.send(arrayBuffer); // Send the file as binary data
                    } else {
                        alert('连接没有开启.');
                    }
                };

                // Read the file as an ArrayBuffer
                reader.readAsArrayBuffer(file);
            }
        }

        // Modify the onmessage handler to handle binary data
        socket.onmessage = function (event) {
            var ta = document.getElementById('responseText');
            if (typeof event.data === 'string') {
                // Handle text
                ta.value = ta.value + '\n' + event.data;
            } else if (event.data instanceof Blob) {
                // Handle binary data
                var blob = event.data;
                var reader = new FileReader();
                reader.onload = function (e) {
                    var dataUrl = e.target.result;
                    ta.value = ta.value + '\n' + 'Received file:' + dataUrl;
                    // If it’s an image, you can display it as well
                    if (blob.type.startsWith('image /')) {
                        var img = new Image();
                        img.src = dataUrl;
                        document.body.appendChild(img); // Just an example of displaying
                    }
                };
                reader.readAsDataURL(blob); // Read the blob as data URL to display/parse
            }
        };

    </script>
</body>

</html>and server var ws = require("nodejs-websocket")

var server = ws.createServer(function (conn) {
    console.log("There are new connections!");

    conn.on("text", function (str) {
        console.log(str);
        boardcast(str);
    });

    conn.on("error", function (err) {
        conn.sendText(err);
    });

    function boardcast(str) {
        var newDate = new Date();
        newDate = newDate.toLocaleString();
        server.connections.forEach(function (conn) {
            conn.sendText(newDate+str);
        });
    }
}).listen(3000, "172.16.10.34");     please Add back-end code to enable file and image transfer