使用Vue、Nodejs以及websocket搭建一个浅近谈天室

[复制链接]
发表于 2025-9-30 06:06:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
说在前面



  • 在学习盘算机网络的时间,看到了websocket这个网络通讯协议,它提供了在单个 TCP 毗连上举行全双工通讯的本领,也就是说不必要客户端哀求就可以主动向客户端发送相应,然后就发现可以用这个做一个谈天功能,于是就有了这篇博客。
  • 下面的谈天室功能还用到了注册登录的干系知识,在我的另一篇博客中有写,链接:vue+nodejs实现登录注册功能
  • 项目的源代码我也发到了github上面,各人可以去获取:github地点,点击跳转
效果展示


websocket



  • 这里我先给各人先容一下websocket协议
websocket的由来



  • 在 WebSocket 出现之前,Web 应用重要依赖于 HTTP 协议举行通讯。然而,HTTP 是一种无状态的、哀求-相应式的协议,每次通讯都必要创建新的毗连,这导致了较高的延长和资源斲丧。为了实实际时通讯,开辟者通常会使用一些变通的方法,如轮询(Polling)或长轮询(Long Polling),但这些方法服从较低。
  • 于是websocket应运而生,WebSocket 协议于 2011 年被正式标准化,旨在办理这些题目,提供一种更高效、更及时的通讯方式。
websocket的特点


  • 全双工通讯:允许服务器和客户端同时发送和吸取消息,而无需等候对方的相应
  • 低延长:一旦websocket毗连创建,数据就可以在客户端和服务器之间快速传输,无需每次都创建新的毗连
  • 轻量级:websocket的数据帧格式简朴,头部开销较小,得当传输小数据包
vue前端



  • 起首我们必要明确搭建一个如许谈天室的步调(以下是波煮本身写项目时间的序次,可参考)

  • 先写出谈天室的静态结构,这里波煮是照着微信的界面画的;
  • 思考用什么存储消息并举行渲染,波煮的脑筋想到的是对象数组,为什么要用对象数组呢?由于我们只用一个数组那么就必要区分这个消息是对方发送的还是本身发送的,从而就行差异的渲染;
  • 然后就是与服务器的链接了,以及一些用户点击事故的绑定。
静态结构



  • 下面的静态结构代码着实已经不静态了,这是绑定事故后的代码了。不外大要还是一样的,这里用到了Element-plus的container组件,
效果


代码

  1. <template>
  2.   <div class="common-layout">
  3.     <el-container>
  4.       <el-aside class="aside" width="200px">
  5.         <el-scrollbar :always="false">
  6.           <!-- 侧边栏用户栏 -->
  7.           <div
  8.             v-for="(item, index) in UserData"
  9.             :key="item.id"
  10.             class="userItem"
  11.             :class="isActive === index ? 'ItemActive' : 'ItemUsual'"
  12.             @click="onChangeUserItem(index)"
  13.           >
  14.             <el-avatar
  15.               style="margin-left: 10px; margin-right: 10px"
  16.               shape="square"
  17.               size="8px"
  18.               :src="item.avator"
  19.             />
  20.             <span>{{ item.username }}</span>
  21.           </div>
  22.         </el-scrollbar>
  23.       </el-aside>
  24.       <el-container>
  25.         <el-header class="header">
  26.           {{ UserData[isActive].username }}
  27.         </el-header>
  28.         <el-main class="main">
  29.           <div
  30.             v-for="(item, index) in Allmessages"
  31.             :class="item.type === 'other' ? 'message_other ' : 'message_my'"
  32.             :key="item.id"
  33.           >
  34.           <div v-if="item.type === 'other'" class="main_message">
  35.             <el-avatar
  36.               :class="item.type === 'other' ? 'other_avatar ' : 'my_avatar'"
  37.               shape="square"
  38.               size="10px"
  39.               :src="item.type === 'other' ? UserData[isActive].avator : CurrentUserName.avator"
  40.             />
  41.             <span :class="item.type === 'other' ? 'other_span ' : 'my_span'">{{ item.message }}</span>
  42.           </div>
  43.           <div v-else class="main_message">
  44.             <span :class="item.type === 'other' ? 'other_span ' : 'my_span'">{{ item.message }}</span>
  45.             <el-avatar
  46.               :class="item.type === 'other' ? 'other_avatar ' : 'my_avatar'"
  47.               shape="square"
  48.               size="10px"
  49.               :src="item.type === 'other' ? UserData[isActive].avator : CurrentUserName.avator"
  50.             />
  51.           </div>
  52.           </div>
  53.             
  54.         </el-main>
  55.         <el-footer class="footer">
  56.           <el-input
  57.             v-model="textarea"
  58.             :rows="7"
  59.             type="textarea"
  60.             placeholder="请输入内容"
  61.             class="InputArea"
  62.             @keydown.enter.exact.prevent="onSubmit"
  63.           />
  64.           <el-button @click="onSubmit" type="primary">发送</el-button>
  65.         </el-footer>
  66.       </el-container>
  67.     </el-container>
  68.   </div>
  69. </template>
  70. <style scoped>
  71. .common-layout {
  72.   width: 700px;
  73.   height: 700px;
  74.   background-color: aquamarine;
  75.   margin: 56px auto;
  76.   display: flex;
  77. }
  78. .aside {
  79.   background-color: white;
  80.   border-left: 1px solid rgb(218, 213, 213);
  81.   border-top: 1px solid rgb(218, 213, 213);
  82. }
  83. .header {
  84.   flex: 0.15;
  85.   background-color: rgb(246, 248, 248);
  86.   text-align: center;
  87.   align-content: center;
  88.   border-bottom: 1px solid rgb(218, 213, 213);
  89.   border-left: 1px solid rgb(218, 213, 213);
  90. }
  91. .main {
  92.   background-color: rgb(246, 248, 248);
  93.   flex: 0.75;
  94.   border-bottom: 1px solid rgb(218, 213, 213);
  95.   border-left: 1px solid rgb(218, 213, 213);
  96.   display: flex;
  97.   flex-direction: column;
  98. }
  99. .main_message{
  100.   display: flex;
  101.   flex-direction: row
  102. }
  103. .footer {
  104.   display: flex;
  105.   justify-content: space-between; /* 子元素水平分布 */
  106.   align-items: flex-end; /* 子元素垂直对齐到容器的底部 */
  107.   padding: 10px; /* 添加一些内边距 */
  108.   background-color: rgb(246, 248, 248);
  109.   border-left: 1px solid rgb(218, 213, 213);
  110.   flex: 0.3;
  111. }
  112. .footer div {
  113.   flex: 1; /* 让文本内容占据剩余空间 */
  114. }
  115. .footer .el-button {
  116.   margin-left: 10px; /* 添加一些左边距,使按钮与文本内容分开 */
  117. }
  118. .message_other {
  119.   background-color: rgb(246, 248, 248);
  120.   width: 200px;
  121.   display: flex;
  122.   justify-content: start;
  123.   align-items: center;
  124.   height: auto;
  125.   margin-bottom: 15px;
  126. }
  127. .message_my {
  128.   background-color: rgb(246, 248, 248);
  129.   width: 200px;
  130.   display: flex;
  131.   justify-content: end;
  132.   align-items: center;
  133.   margin-bottom: 15px;
  134.   margin-left: 250px;
  135. }
  136. .userItem {
  137.   height: 70px;
  138.   background-color: white;
  139.   display: flex;
  140.   align-items: center;
  141. }
  142. .ItemActive {
  143.   background-color: rgb(231, 233, 233);
  144. }
  145. .my_span{
  146.   padding: 5px;
  147.   background-color: greenyellow;
  148.   line-height: 30px;
  149. }
  150. .my_avatar{
  151.   margin-right: 10px;
  152.   margin-left: 10px
  153. }
  154. .other_span{
  155.   padding: 5px;
  156.   background-color: white;
  157.   line-height: 30px
  158. }
  159. .other_avatar{
  160.   margin-left: 10px;
  161.   margin-right: 10px
  162. }
  163. </style>
复制代码
点击切换用户以及该用户高亮

实现思绪


  • 界说一个相应式数据来纪录当前在和哪个用户谈天
  1. //当前用户
  2. const isActive = ref(0);
复制代码

  • 通过isActive来进举措态绑定类名,从而实现差异的css样式,这个是vue的方便之处,可以直接使用:class来实现动态类名的绑定,这里高亮区分我是通过设置差异的配景颜色来区分的
  1. :class="isActive === index ? 'ItemActive' : 'ItemUsual'"
复制代码
  1. .ItemActive {
  2.   background-color: rgb(231, 233, 233);
  3. }
复制代码

  • 绑定点击事故,获取当前用户的index,或修改isActive相应式数据为当前用户的index
  1. //切换用户回调函数
  2. const onChangeUserItem = (index) => {
  3.   isActive.value = index;
  4. };
复制代码
效果展示


发送消息功能



  • 我们先来理清团体思绪:起首点击发送时必要获取文本框的内容,并把这个内容添加到消息数组中,接着把输入框中的内容清空。

  • 点击发送时获取文本框内容,先界说一个相应式数据与输入框举行双向绑定:
  1. //文本输入区域
  2. const textarea = ref("");
  3. //通过v-model双向绑定
  4. <el-input
  5.        v-model="textarea"
  6.        :rows="7"
  7.        type="textarea"
  8.        placeholder="请输入内容"
  9.        class="InputArea"
  10.        @keydown.enter.exact.prevent="onSubmit"
  11. />
复制代码

  • 为发送按钮添加点击事故,并将信息以对象的情势添加到消息数组中
  1. //点击发送的回调函数
  2. const onSubmit = () => {
  3.   //获取当前用户用户名
  4.   console.log(UserData.value[isActive.value].username);
  5.   const toname = UserData.value[isActive.value].username;
  6.   //将消息发送给服务端再由服务端推送给指定用户
  7.   const json = {
  8.     type: "message",
  9.     toName: toname,
  10.     message: textarea.value,
  11.   };
  12.   Allmessages.value.push({
  13.     type:"my",
  14.     id:id.value,
  15.     message:textarea.value
  16.   })
  17.   id.value++
  18.   //向服务端发送该消息
  19.   socket.send(JSON.stringify(json));
  20.   textarea.value = "";
  21. };
复制代码
效果展示


毗连服务端



  • 由于我们用的是websocket协议,以是我们必要创建一个websocket毗连,再监听毗连以及websocket的错误

  • 创建websocket毗连:
  1. //创建websocket连接
  2. const socket = new WebSocket("http://localhost:3000");
复制代码

  • 监听毗连,在这内里必要在刚开始毗连上服务器的时间向服务器发送该用户的信息,以便服务器向别的用户广播该用户的上线状态。
  • 监听服务器发来的消息,这里也就是别人向你发送过来的消息,别人先将要对你发送的消息发送给服务器,然后再由服务器根据一些条件发送给你。 服务器就像一个中介一样,链接这你们两个
  • 拿到服务器发送给你的消息并插入到消息列表中举行渲染
  1. //创建websocket连接
  2. const socket = new WebSocket("http://localhost:3000");
  3. //监听websocket链接socket.onopen = async () => {  //获取用户信息  const token = localStorage.getItem("token");  const res = await axios.get("http://0.0.0.0:8080/my/info", {    headers: {      Authorization: token,    },  });  // console.log(res,"userinfo");  CurrentUserName.value.username = res.data.data.username;  CurrentUserName.value.isOnline = true;  CurrentUserName.value.avator = res.data.data.user_pic;  // console.log("毗连到服务器");  socket.send(    JSON.stringify({ type: "userInfo", data: CurrentUserName.value })  );};//监听服务器消息socket.onmessage = (event) => {  // const message = event.data;  const message = JSON.parse(event.data);  console.log(message, "message");  // CurrentUserName.value = message.user  if (message.type === "message") {    // console.log(message,"jijiy");    Allmessages.value.push({      type:"other",      id:id.value,      message:message.message    });    id.value++;    // console.log(message_other.value, "value");  }  if (message.type === "1") {    UserData.value = message.users.filter((item) => {      return item.username !== CurrentUserName.value.username;    });    //体现进入谈天室    ElMessage({      message: message.message,      type: "success",    });    //将该用户加入  }  if (message.type === 0) {    //体现退出谈天室    ElMessage(message.message);  }};//监听websocket错误socket.onerror = (err) => {  console.log("Websocket错误:", err);};
复制代码
Nodejs服务器端

实现步调



  • 下面是服务器端的websocket实现步调:

  • 创建 WebSocket 服务器
    使用 WebSocket.Server 创建了一个 WebSocket 服务器,绑定到一个 HTTP 服务器(HttpServer)上。
  1. //创建Websocket服务器
  2. const wss = new WebSocket.Server({ server: HttpServer });
复制代码

  • 存储毗连的客户端
    使用一个 Map 对象(clients)来存储当前毗连的客户端及其用户信息。
    Map 的键是WebSocket毗连对象(ws),值是用户信息(userInfo)。
  1. //存储连接的客户端
  2. const clients = new Map();
复制代码

  • 判定用户是否已存在
    通过函数isSaveInClients,用于查抄某个用户名是否已经存在于 clients 中。通过将 clients 的值转换为数组并查抄是否包罗指定的用户名来实现。
  1. //判断用户是否存在于clients中
  2. const isSaveInClients = (username)=>{
  3.   const clientsArray = [...clients.values()];
  4.   if(clientsArray.includes(`username:${username}`)){
  5.     return true
  6.   }
  7.   return false
  8. }
复制代码

  • 客户端毗连处理惩罚
    当客户端通过 WebSocket 毗连时,触发 connection 事故。
    每个毗连的客户端都会绑定以下事故监听器:

    • 吸取消息
      监听 message 事故,处理惩罚客户端发送的消息。
      消息以 JSON 格式传输,包罗 type 和 data 字段。
      用户信息(type: “userInfo”):
      如果客户端发送的是用户信息,服务器会查抄该用户是否已经存在于 clients 中。
      如果用户不存在,则将用户信息存储到 clients 中,并广播一条消息给全部客户端,关照新用户已进入谈天室。
    • 谈天信息(type: "message"):
      如果客户端发送的是谈天信息,服务器会查找目的用户(data.toName)。
      如果找到目的用户且其 WebSocket 毗连处于打开状态,则将谈天信息发送给目的用户。

  1. wss.on("connection", (ws) => {
  2.   var userInfo = {};
  3.   //监听websocket连接
  4.   ws.on("message", (message) => {
  5.     const data = JSON.parse(message);
  6.     //如果传入的是用户信息
  7.     if (data.type == "userInfo") {
  8.       //判断该用户是否已经在clients中
  9.       if(isSaveInClients(data.data.username)){
  10.         return
  11.       }
  12.       // console.log("进来了");
  13.       //如果客户端发送来的是用户信息
  14.       userInfo = data.data;
  15.       clients.set(ws, userInfo);
  16.       // console.log(clients.values(), "clients");
  17.       //将map转为array
  18.       const clientsArray = [...clients.values()];
  19.       //广播消息给所有客户端
  20.       for (const [clientWs, clientUserInfo] of clients) {
  21.         //给其他用户广播有新用户登录
  22.         if (clientWs.readyState === WebSocket.OPEN) {
  23.           // console.log("进来了广播");
  24.           clientWs.send(
  25.             JSON.stringify({
  26.               type: "1",
  27.               user: {
  28.                 username: userInfo.username,
  29.                 isOnline: true,
  30.               },
  31.               message: `${userInfo.username}进入聊天室`,
  32.               users: clientsArray,
  33.             })
  34.           );
  35.         }
  36.       }
  37.     }
  38.     //如果传入的是聊天信息
  39.     if(data.type === "message"){
  40.       // console.log("传入的是聊天信息");
  41.       console.log(data,"聊天信息");
  42.       for(const [clientWs,clientUserInfo] of clients){
  43.         if(clientUserInfo.username === data.toName && clientWs.readyState === WebSocket.OPEN){
  44.           clientWs.send(JSON.stringify({
  45.             type:"message",
  46.             message:data.message
  47.           }))
  48.         }
  49.       }
  50.     }
  51.     //  console.log("收到消息", data);
  52.   });
复制代码

  • 客户端断开毗连
    监听 close 事故,处理惩罚客户端断开毗连的环境。
    当客户端断开毗连时,服务器会广播一条消息给全部客户端,关照该用户已退出谈天室。
    然后从 clients 中删除该客户端的纪录。
  1.   //监听客户端断开连接
  2.   ws.on("close", () => {
  3.     // console.log(username +"退出聊天室");
  4.     //退出聊天室广播
  5.     for (const [clientWs,clientUserInfo] of clients) {
  6.       if (clientWs.readyState === WebSocket.OPEN) {
  7.         clientWs.send(
  8.           JSON.stringify({
  9.             type: "0",
  10.             user: {
  11.               username: userInfo.username,
  12.               isOnline: true,
  13.             },
  14.             message: `${userInfo.username}退出聊天室`,
  15.           })
  16.         );
  17.       }
  18.     }
  19.     clients.delete(ws);
  20.   });
  21. });
复制代码

  • 启动服务器
    界说了一个端标语 PORT(3000),并启动 HTTP 服务器。
    服务器运行后,会监听指定端口,并在控制台输出服务器的地点。
  1. //启动服务器
  2. const PORT = 3000;
  3. HttpServer.listen(PORT, () => {
  4.   console.log(`服务器运行在 http://localhost:${PORT}`);
  5. });
复制代码
代码

  1. //创建Websocket服务器
  2. const wss = new WebSocket.Server({ server: HttpServer });
  3. //存储连接的客户端
  4. const clients = new Map();
  5. //判断用户是否存在于clients中
  6. const isSaveInClients = (username)=>{
  7.   const clientsArray = [...clients.values()];
  8.   if(clientsArray.includes(`username:${username}`)){
  9.     return true
  10.   }
  11.   return false
  12. }
  13. //客户端毗连wss.on("connection", (ws) => {
  14.   var userInfo = {};
  15.   //监听websocket连接
  16.   ws.on("message", (message) => {
  17.     const data = JSON.parse(message);
  18.     //如果传入的是用户信息
  19.     if (data.type == "userInfo") {
  20.       //判断该用户是否已经在clients中
  21.       if(isSaveInClients(data.data.username)){
  22.         return
  23.       }
  24.       // console.log("进来了");
  25.       //如果客户端发送来的是用户信息
  26.       userInfo = data.data;
  27.       clients.set(ws, userInfo);
  28.       // console.log(clients.values(), "clients");
  29.       //将map转为array
  30.       const clientsArray = [...clients.values()];
  31.       //广播消息给所有客户端
  32.       for (const [clientWs, clientUserInfo] of clients) {
  33.         //给其他用户广播有新用户登录
  34.         if (clientWs.readyState === WebSocket.OPEN) {
  35.           // console.log("进来了广播");
  36.           clientWs.send(
  37.             JSON.stringify({
  38.               type: "1",
  39.               user: {
  40.                 username: userInfo.username,
  41.                 isOnline: true,
  42.               },
  43.               message: `${userInfo.username}进入聊天室`,
  44.               users: clientsArray,
  45.             })
  46.           );
  47.         }
  48.       }
  49.     }
  50.     //如果传入的是聊天信息
  51.     if(data.type === "message"){
  52.       // console.log("传入的是聊天信息");
  53.       console.log(data,"聊天信息");
  54.       for(const [clientWs,clientUserInfo] of clients){
  55.         if(clientUserInfo.username === data.toName && clientWs.readyState === WebSocket.OPEN){
  56.           clientWs.send(JSON.stringify({
  57.             type:"message",
  58.             message:data.message
  59.           }))
  60.         }
  61.       }
  62.     }
  63.     //  console.log("收到消息", data);
  64.   });
  65.   //监听客户端断开连接
  66.   ws.on("close", () => {
  67.     // console.log(username +"退出聊天室");
  68.     //退出聊天室广播
  69.     for (const [clientWs,clientUserInfo] of clients) {
  70.       if (clientWs.readyState === WebSocket.OPEN) {
  71.         clientWs.send(
  72.           JSON.stringify({
  73.             type: "0",
  74.             user: {
  75.               username: userInfo.username,
  76.               isOnline: true,
  77.             },
  78.             message: `${userInfo.username}退出聊天室`,
  79.           })
  80.         );
  81.       }
  82.     }
  83.     clients.delete(ws);
  84.   });
  85. });
  86. //启动服务器
  87. const PORT = 3000;
  88. HttpServer.listen(PORT, () => {
  89.   console.log(`服务器运行在 http://localhost:${PORT}`);
  90. });
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表