<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <style>
        body {
            background-color: darkgray;
        }

        #main, #register {
            margin-left: auto;
            margin-right: auto;
            width: 400px;
        }

        #main {
            display: none;
        }

        textarea {
            width: 100%;
            height: 300px;
        }

        input, button {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div id="main">
        <div>
            <span id="nameData"></span>
            <button id="closeButton" onclick="closeConnection()">断开连接</button>
        </div>
        <textarea id="responseText" readonly></textarea>
        <div>
            <input type="text" id="message">
            <button onclick="sendMessage()">发送消息</button>
            <button onclick="clearChat()">清空聊天记录</button>
        </div>
        <div>
            <input type="file" id="fileInput">
            <button onclick="sendFile()">发送文件</button>
        </div>
    </div>
    <div id="register">
        <input id="name" type="text" placeholder="请输入你在聊天中的名字">
        <button onclick="connectToServer()">连接到服务器</button>
    </div>
    <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>
    <script type="text/javascript">
        var socket, name;

        function connectToServer() {
            name = document.getElementById("name").value.trim();
            if (name) {
                socket = new WebSocket("ws://localhost:3000"); // Replace localhost with your server IP if needed
                document.getElementById("register").style.display = "none";
                document.getElementById("main").style.display = "block";
                document.getElementById("nameData").textContent = "当前用户：" + name;

                socket.onopen = function() {
                    writeToChat("连接开启!");
                };

                socket.onclose = function() {
                    writeToChat("连接被关闭");
                    document.getElementById("main").style.display = "none";
                    document.getElementById("register").style.display = "block";
                };

                socket.onmessage = function(event) {
                    var data = JSON.parse(event.data);
                    switch (data.type) {
                        case 'text':
                            writeToChat(data.name + ': ' + data.content);
                            break;
                        case 'file':
                            var link = document.createElement('a');
                            link.href = 'data:' + data.contentType + ';base64,' + data.content;
                            link.download = data.name;
                            link.textContent = "Download " + data.name;
                            link.style.display = 'block';
                            document.getElementById('responseText').appendChild(link);
                            break;
                        case 'image':
                            writeToChat(data.name + " sent an image:");
                            var img = new Image();
                            img.src = 'data:' + data.contentType + ';base64,' + data.content;
                            img.style.maxWidth = '200px';
                            img.style.display = 'block';
                            document.getElementById('responseText').appendChild(img);
                            break;
                        default:
                            console.error("Unknown message type:", data.type);
                    }
                };
            } else {
                alert("请填写您的名字！");
            }
        }

        function sendMessage() {
            var messageInput = document.getElementById("message");
            var message = messageInput.value.trim();
            if (message && socket.readyState === WebSocket.OPEN) {
                var data = { type: "text", name: name, content: message };
                socket.send(JSON.stringify(data)); // Send JSON string to server
                messageInput.value = "";
            } else {
                alert("连接没有开启或消息为空.");
            }
        }

        function closeConnection() {
            if (socket) {
                socket.close();
            }
        }

        function clearChat() {
            document.getElementById("responseText").value = "";
        }

        function writeToChat(message) {
            var chat = document.getElementById("responseText");
            chat.value += (chat.value ? "\n" : "") + message;
        }

        function sendFile() {
            var fileInput = document.getElementById("fileInput");
            var file = fileInput.files[0];

            if (file && socket.readyState === WebSocket.OPEN) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    var data = {
                        type: file.type.startsWith("image/") ? "image" : "file",
                        name: file.name,
                        content: event.target.result.split("base64,")[1],
                        contentType: file.type
                    };
                    socket.send(JSON.stringify(data)); // Send JSON string to server
                };

                // Read the file and trigger reader.onload
                reader.readAsDataURL(file);
                fileInput.value = ""; // Reset the input
            } else {
                alert("连接没有开启或未选择文件.");
            }
        }
    </script>
</body>
</html> 这是前端  const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 3000 });

server.on("connection", function (ws) {
    ws.on("message", function (message) {
        // Broadcast messages to all clients as JSON strings
        server.clients.forEach(function each(client) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    ws.on("close", function () {
        console.log("A client has disconnected");
    });
});

console.log("Server is running on ws://localhost:3000");这是后端 修改代码 实现 文字 收发     图片发送后可以在聊天框预览的功能