前端聊天室

<!DOCTYPE html><html><head>  <title>Socket.IO 聊天室</title>  <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>  <style>    .chat-box { height: 400px; border: 1px solid #ccc; overflow-y: auto; padding: 10px; }    .message { margin: 8px 0; padding: 8px; border-radius: 4px; }    .self { background: #e3f2fd; margin-left: 20%; }    .others { background: #f5f5f5; margin-right: 20%; }    #user-list { position: fixed; right: 20px; top: 20px; background: white; padding: 10px; border: 1px solid #ddd; }  </style></head><body>  <div id="user-list"></div>  <div class="chat-box" id="chatBox"></div>  <input type="text" id="messageInput" placeholder="输入消息..." style="width: 70%">  <button onclick="sendMessage()">发送</button>  <script>    // 初始化连接    const socket = io('wss://your-chat-server.com', {      auth: { userId: localStorage.getItem('userId') || `user_${Date.now()}` },      reconnectionAttempts: 3,      transports: ['websocket']    });    // 消息发送函数    function sendMessage() {      const input = document.getElementById('messageInput');      if (input.value.trim()) {        socket.emit('chatMessage', {          text: input.value,          time: new Date().toISOString()        });        input.value = '';      }    }    // 监听服务端消息    socket.on('chatMessage', (msg) => {      const isSelf = msg.userId === socket.auth.userId;      const div = document.createElement('div');      div.className = `message ${isSelf ? 'self' : 'others'}`;      div.innerHTML = `<b>${msg.nickname}</b>: ${msg.text}<br><small>${new Date(msg.time).toLocaleTimeString()}</small>`;      document.getElementById('chatBox').appendChild(div);    });    // 用户列表更新    socket.on('userListUpdate', (users) => {      document.getElementById('user-list').innerHTML =         `<h4>在线用户 (${users.length})</h4>` +         users.map(u => `<div>${u.nickname}</div>`).join('');    });    // 连接状态管理    socket.on('connect', () => {      console.log('已连接服务器');      socket.emit('joinRoom', 'public');    });    socket.on('disconnect', () => {      console.warn('连接已断开');    });    // 回车发送    document.getElementById('messageInput').addEventListener('keypress', (e) => {      if (e.key === 'Enter') sendMessage();    });  </script></body></html>

二、核心功能说明

  1. 连接配置

    • 自动生成用户 ID 并存储于 localStorage

    • 优先使用 WebSocket 协议,失败后自动重连

  2. 消息交互

    • 支持文本消息发送与格式化时间显示

    • 消息气泡区分自己/他人(CSS 样式控制)

  3. 状态管理

    • 实时更新在线用户列表

    • 自动加入默认公共聊天室 public


三、服务端需配合实现

虽然此示例为纯前端代码,但需服务端支持以下逻辑:

  1. 处理 joinRoom 事件管理房间

  2. 广播 chatMessage 到同一房间用户

  3. 维护用户连接状态并推送 userListUpdate


四、扩展建议

  1. 历史记录
    添加 localStorage 缓存最近的 100 条消息

  2. 文件传输
    通过 socket.emit('fileUpload', base64Data) 实现(需服务端支持)

  3. 心跳检测
    增加 setInterval 发送心跳包维持连接


标签:

相关文章

海量数据分布式处理

若数据量达到 ‌千万级或 TB 级‌,可结合消息队列(如 RabbitMQ、Kafka)实现分布式消费:// 生产者:将数据分块推送至队列 $redis = new&n...

UniApp小程序端数据持久化

在UniApp开发小程序时,数据持久化是确保应用功能完整性和用户体验的关键技术。本指南将详细介绍UniApp小程序端数据持久化的多种方案、平台差异、容量限制以及最佳实践。一、基础持久化方案1. 本地存...

Vue Composition API的快速上手指南

一、基础搭建‌创建组件入口‌使用setup()函数替代传统选项式API,作为组件逻辑的主入口       可通过 <script setup&g...

Vue3 的生命周期钩子

Vue3 的生命周期钩子函数是组件从创建到销毁过程中各个阶段的关键节点,以下是主要特点和使用方式:一、核心生命周期钩子(Composition API)setup()替代了 Vue2 的 before...

需要前端技术的主要行业分类

前端开发作为连接用户与数字产品的桥梁,其应用场景已渗透到几乎所有数字化领域。以下是需要前端技术的主要行业分类及特点:‌互联网行业‌小程序开发(微信、支付宝等)成为新兴增长点,市场持续存在人才缺口‌传统...

PHP高级编程示例项目

<?php namespace App\Controllers; use App\Models\User; use Exception; class...