发送 <script> // WebSocket 聊天室实现const socket = new WebSocket('wss://YOUR_SERVER_ADDRESS/chat');socket.addEventListener('open', () => {console.log('WebSocket 连接已建立!');});socket.addEventListener('message', (event) => {// 处理收到的消息const data = JSON.parse(event.data);if (data.type === 'message') {// 显示聊天消息addMessage(data.message);}});socket.addEventListener('close', () => {console.log('WebSocket 连接已关闭!');});const chatMessages = document.querySelector('.chat-messages');const chatInput = document.querySelector('.chat-input');const chatForm = document.querySelector('.chat-form');function addMessage(message) {// 创建一个新的聊天消息元素const messageElement = document.createElement('p');messageElement.textContent = message;// 将消息元素添加到聊天室消息容器中chatMessages.appendChild(messageElement);// 滚动聊天室消息容器到最底部chatMessages.scrollTop = chatMessages.scrollHeight;}chatForm.addEventListener('submit', (event) => {event.preventDefault();// 从输入框中获取消息内容const message = chatInput.value;// 清空输入框chatInput.value = '';// 发送消息到服务器socket.send(JSON.stringify({type: 'message',message: message}));}); </script>