• 前端websocket打造实时聊天室



    前言

    前端运用websocket打造的实时消息通知的聊天室,语言采用了JavaScript,可以进行登录系统,多用户实时聊天,后端服务器采用nodejs编写(我会把代码直接贴上)

    代码是用最原生的js写的,如果利用框架例如vue,angular等,代码会变的更少更简洁


    1、登陆页面

    1.1 entry.html

    <body>
      <input type="text" id="username" placeholder="请输入用户名" />
      <button id="enter">进入聊天室button>
    
      <script src="./js/entry.js">script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.2 entry.js

    ((doc, localStorage, location) => {
      const oUsername = doc.querySelector("#username");
      const oEnterBtn = doc.querySelector("#enter");
    
      const init = () => {
        bindEvent();  // 执行绑定事件
      };
    
      function bindEvent() {
        oEnterBtn.addEventListener("click", handleEnterBtnClick, false); // 给按钮添加点击事件
      }
    
      function handleEnterBtnClick() {
        const username = oUsername.value.trim(); // 去掉登录名的前后空格
    
        if (username.length < 6) {
          alert("用户名不小于6位");	// 登录名不能小于6位
          return;
        }
        
        localStorage.setItem("username", username);  // 把登录名存到localstorage里面
        location.href = "index.html";  // 跳转到聊天页面
      }
    
      init(); // 调用初始化函数
      
    })(document, localStorage, location); // 立即执行函数
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    界面如下:

    在这里插入图片描述
    输入用户名进入到聊天室:
    在这里插入图片描述
    点击进入聊天室按钮:
    在这里插入图片描述
    下面继续说index这个聊天页面


    2、聊天页面

    2.1 index.html

    <body>
        <ul id="list">ul>   
        <input type="text" id="message" placeholder="请输入消息">
        <button id="send">发送button>
    
        <script src="./js/index.js">script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.2 index.js

    ((document, WebSocket) => {
      const oList = document.querySelector("#list");
      const oMessage = document.querySelector("#message");
      const oSendBtn = document.querySelector("#send");
    
      // 协议是ws,不是http
      const ws = new WebSocket("ws:localhost:8000");
      // 新建WebSocket实例 因为我用nodejs写的服务器的地址是localhost:8000,如果大家开发的话,问后端要这个websocket地址即可。
    
      let username = "";
    
      const init = () => {
        bindEvent();
      };
    
      function bindEvent() {
        oSendBtn.addEventListener("click", handleSendBtnClick, false); // 给发送按钮绑定点击事件
        
        // 实例对象的onopen属性,用于指定连接成功后的回调函数。也就是open事件,也可以写作 ws.onopen = function () {}
        ws.addEventListener("open", handleOpen, false); 
        ws.addEventListener("close", handleClose, false); // 同上
        ws.addEventListener("error", handleError, false); // 同上
        // 实例对象的onmessage属性,用于指定收到服务器数据后的回调函数。
        ws.addEventListener("message", handleMessage, false); 
      }
    
      // 发送按钮的点击事件
      function handleSendBtnClick() {
        console.log("send message");
    
        const msg = oMessage.value; // 发送的内容(input框的value值)
        if (!msg.trim().length) {
          return;
        }
    
        // 实例对象的send()方法用于向服务器发送数据。
        ws.send(
    	  // 应该发送字符串
          JSON.stringify({
            user: username,
            dateTime: new Date().getTime(),
            message: msg,
          })
        );
    
    	// 发送完以后清空输入框
        oMessage.value = "";
      }
    
      function handleOpen(e) {
        console.log("Websocket open", e);
        // 获取登录时存放在localStorage的登录名
        username = localStorage.getItem("username");
    
    	// 如果没找到登录名,则跳转到登录页面重新登录
        if (!username) {
          location.href = "entry.html";
        }
      }
      function handleClose(e) {
        console.log("Websocket close", e);
      }
      function handleError(e) {
        console.log("Websocket error", e);
      }
      function handleMessage(e) {
        console.log("Websocket message--收到消息了", e);
        const msgData = JSON.parse(e.data);
        // 向页面里的ul标签添加子节点
        oList.appendChild(createMsg(msgData));
      }
    
      // 消息的格式
      function createMsg(data) {
        const { user, dateTime, message } = data;
        const oItem = document.createElement("li");
        oItem.innerHTML = `
        

    ${user} ${new Date(dateTime)}

    消息:${message}

    `
    ; return oItem; } init(); })(document, WebSocket); // WebSocket是window身上本身就有的
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88

    3、nodejs搭建的服务器

    const Ws = require("ws");
    
    ((Ws) => {
      // ws:localhost:8000
      const server = new Ws.Server({ port: 8000 });
    
      const init = () => {
        bindEvent();
      };
    
      function bindEvent() {
        server.on("open", handleOpen);
        server.on("close", handleClose);
        server.on("error", handleError);
        server.on("connection", handleConnection);
      }
    
      function handleOpen() {
        console.log("Websocket open");
      }
      function handleClose() {
        console.log("Websocket close");
      }
      function handleError() {
        console.log("Websocket error");
      }
      function handleConnection(ws) {
        console.log("Websocket connected");
        ws.on("message", handleMessage);
      }
      function handleMessage(msg) {
        // 接受前端发送过来的message
        msg = msg.toString("utf-8");
        console.log("msg---", msg);
    
        // 把消息广播出去,凡是连接这个websocket地址的都能收到
        server.clients.forEach((c) => {
          c.send(msg);
        });
      }
    
      init();
    })(Ws);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    4、目录结构

    在这里插入图片描述

    5、实操结果


    1、输入用户名登录进聊天室页面 (chrome浏览器标签页

    在这里插入图片描述
    2、输入用户名登录进聊天室页面 (360浏览器标签页
    在这里插入图片描述

    3、chrome的tom发送消息:

    在这里插入图片描述
    4、chrome的tom 和 360的jerry都可以收到消息:

    在这里插入图片描述
    在这里插入图片描述
    5、360的Jerry发消息,两者也都能收到,自行尝试

  • 相关阅读:
    ChatGPT工作提效之使用python开发对接百度地图开放平台API的实战方案(批量路线规划、批量获取POI、突破数量有限制、批量地理编码)
    灵活用工系统开发优势在哪里?
    java计算机毕业设计交通非现场执法系统MyBatis+系统+LW文档+源码+调试部署
    git 删除远程非主分支
    Android开发_记事本(1)
    Sparse稀疏检索介绍与实践
    查看日志.
    服务的网关-Zuul(1.5.x)
    数据库表中创建字段查询出来却为NULL?
    Web(一)Web前端开发概述
  • 原文地址:https://blog.csdn.net/qq_42667613/article/details/126117235