欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue使用WebSocket模擬實(shí)現(xiàn)聊天功能

 更新時(shí)間:2021年08月12日 11:30:20   作者:程程0221  
這篇文章主要介紹了vue使用WebSocket模擬實(shí)現(xiàn)聊天功能,通過(guò)創(chuàng)建node服務(wù)和server.js文件實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下

效果展示 兩個(gè)瀏覽器相互模擬

在這里插入圖片描述

在這里插入圖片描述

1.創(chuàng)建模擬node服務(wù)

在vue根目錄下創(chuàng)建 server.js 文件模擬后端服務(wù)器

在這里插入圖片描述

**在server終端目錄下載 **

npm install --s ws

2.編寫server.js文件

代碼如下

var userNum = 0; //統(tǒng)計(jì)在線人數(shù)
var chatList = [];//記錄聊天記錄
var WebSocketServer = require('ws').Server;
wss = new WebSocketServer({ port: 8181 }); //8181 與前端相對(duì)應(yīng)
//調(diào)用 broadcast 廣播,實(shí)現(xiàn)數(shù)據(jù)互通和實(shí)時(shí)更新
wss.broadcast = function (msg) {
    wss.clients.forEach(function each(client) {
        client.send(msg);
    });
};
wss.on('connection', function (ws) {
    userNum++;//建立連接成功在線人數(shù) +1
    wss.broadcast(JSON.stringify({ funName: 'userCount', users: userNum, chat: chatList })); //建立連接成功廣播一次當(dāng)前在線人數(shù)
    console.log('Connected clients:', userNum);
    //接收前端發(fā)送過(guò)來(lái)的數(shù)據(jù)
    ws.on('message', function (e) {
        var resData = JSON.parse(e)
        console.log('接收到來(lái)自clent的消息:' + resData.msg)
        chatList.push({ userId: resData.userId, content: resData.msg });//每次發(fā)送信息,都會(huì)把信息存起來(lái),然后通過(guò)廣播傳遞出去,這樣此每次進(jìn)來(lái)的用戶就能看到之前的數(shù)據(jù)
        wss.broadcast(JSON.stringify({ userId: resData.userId, msg: resData.msg })); //每次發(fā)送都相當(dāng)于廣播一次消息

    });
    ws.on('close', function (e) {
        userNum--;//建立連接關(guān)閉在線人數(shù) -1
        wss.broadcast(JSON.stringify({ funName: 'userCount', users: userNum, chat: chatList }));//建立連接關(guān)閉廣播一次當(dāng)前在線人數(shù)
        console.log('Connected clients:', userNum);
        console.log('長(zhǎng)連接已關(guān)閉')
    })
})
console.log('服務(wù)器創(chuàng)建成功')

然后npm run start啟動(dòng)服務(wù)器

3.vue前端頁(yè)面

代碼如下

<template>
  <div class="chat-box">
    <header>聊天室人數(shù):{{count}}</header>
    <div class="msg-box" ref="msg-box">
      <div
        v-for="(i,index) in list"
        :key="index"
        class="msg"
        :style="i.userId == userId?'flex-direction:row-reverse':''"
      >
        <div class="user-head">
          <div
            class="head"
            :style="` background: hsl(${getUserHead(i.userId,'bck')}, 88%, 62%); clip-path:polygon(${getUserHead(i.userId,'polygon')}% 0,100% 100%,0% 100%); transform: rotate(${getUserHead(i.userId,'rotate')}deg)`"
          ></div>
        </div>
        <div class="user-msg">
          <span
            :style="i.userId == userId?'float: right':''"
            :class="i.userId == userId?'right':'left'"
          >{{i.content}}</span>
        </div>
      </div>
    </div>
    <div class="input-box">
      <input type="text" ref="sendMsg" v-model="contentText" @keyup.enter="sendText()" />
      <div class="btn" :class="{['btn-active']:contentText}" @click="sendText()">發(fā)送</div>
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      ws: null,
      count: 0,
      userId: null, //當(dāng)前用戶ID
      list: [], //聊天記錄的數(shù)組
      contentText: "", //input輸入的值
    };
  },
  created() {
    this.getUserID();
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    //根據(jù)時(shí)間戳作為當(dāng)前用戶ID
    getUserID() {
      let time = new Date().getTime();
      this.userId = time;
    },
    //根據(jù)userID生成一個(gè)隨機(jī)頭像
    getUserHead(id, type) {
      let ID = String(id);
      if (type == "bck") {
        return Number(ID.substring(ID.length - 3));
      }
      if (type == "polygon") {
        return Number(ID.substring(ID.length - 2));
      }
      if (type == "rotate") {
        return Number(ID.substring(ID.length - 3));
      }
    },
    //滾動(dòng)條到底部
    scrollBottm() {
      let el = this.$refs["msg-box"];
      el.scrollTop = el.scrollHeight;
    },
    //發(fā)送聊天信息
    sendText() {
      let _this = this;
      _this.$refs["sendMsg"].focus();
      if (!_this.contentText) {
        return;
      }
      let params = {
        userId: _this.userId,
        msg: _this.contentText,
      };
      _this.ws.send(JSON.stringify(params)); //調(diào)用WebSocket send()發(fā)送信息的方法
      _this.contentText = "";
      setTimeout(() => {
        _this.scrollBottm();
      }, 500);
    },
    //進(jìn)入頁(yè)面創(chuàng)建websocket連接
    initWebSocket() {
      let _this = this;
      //判斷頁(yè)面有沒(méi)有存在websocket連接
      if (window.WebSocket) {
        // 此處的 :8181 端口號(hào) 要與后端配置的一致
        let ws = new WebSocket("ws://192.168.5.42:9502"); 
        // let ws = new WebSocket("ws://192.168.5.8:8181"); //這里是我本地測(cè)試
        _this.ws = ws;
        ws.onopen = function (e) {
          console.log("服務(wù)器連接成功");
        };
        ws.onclose = function (e) {
          console.log("服務(wù)器連接關(guān)閉");
        };
        ws.onerror = function () {
          console.log("服務(wù)器連接出錯(cuò)");
        };
        ws.onmessage = function (e) {
          //接收服務(wù)器返回的數(shù)據(jù)
          let resData = JSON.parse(e.data);
          if (resData.funName == "userCount") {
            _this.count = resData.users;
            _this.list = resData.chat;
          } else {
            _this.list = [
              ..._this.list,
              { userId: resData.userId, content: resData.msg },
            ];
          }
        };
      }
    },
  },
};
</script>
 
<style lang="scss" scoped>
.chat-box {
  margin: 0 auto;
  background: #fafafa;
  position: absolute;
  height: 100%;
  width: 100%;
  // max-width: 700px;
  header {
    position: fixed;
    width: 100%;
    height: 3rem;
    background: #409eff;
    // max-width: 700px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bold;
    color: white;
    font-size: 1rem;
  }
  .msg-box {
    position: absolute;
    height: calc(100% - 6.5rem);
    width: 100%;
    margin-top: 3rem;
    overflow-y: scroll;
    .msg {
      width: 95%;
      min-height: 2.5rem;
      margin: 1rem 0.5rem;
      position: relative;
      display: flex;
      justify-content: flex-start !important;
      .user-head {
        min-width: 2.5rem;
        width: 20%;
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        background: #f1f1f1;
        display: flex;
        justify-content: center;
        align-items: center;
        .head {
          width: 1.2rem;
          height: 1.2rem;
        }
        // position: absolute;
      }
      .user-msg {
        width: 80%;
        // position: absolute;
        word-break: break-all;
        position: relative;
        z-index: 5;
        span {
          display: inline-block;
          padding: 0.5rem 0.7rem;
          border-radius: 0.5rem;
          margin-top: 0.2rem;
          font-size: 0.88rem;
        }
        .left {
          background: white;
          animation: toLeft 0.5s ease both 1;
        }
        .right {
          background: #53a8ff;
          color: white;
          animation: toright 0.5s ease both 1;
        }
        @keyframes toLeft {
          0% {
            opacity: 0;
            transform: translateX(-10px);
          }
          100% {
            opacity: 1;
            transform: translateX(0px);
          }
        }
        @keyframes toright {
          0% {
            opacity: 0;
            transform: translateX(10px);
          }
          100% {
            opacity: 1;
            transform: translateX(0px);
          }
        }
      }
    }
  }
  .input-box {
    padding: 0 0.5rem;
    position: absolute;
    bottom: 0;
    width: 97%;
    height: 3.5rem;
    background: #fafafa;
    box-shadow: 0 0 5px #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    input {
      height: 2.3rem;
      display: inline-block;
      width: 100%;
      padding: 0.5rem;
      border: none;
      border-radius: 0.2rem;
      font-size: 0.88rem;
    }
    .btn {
      height: 2.3rem;
      min-width: 4rem;
      background: #e0e0e0;
      padding: 0.5rem;
      font-size: 0.88rem;
      color: white;
      text-align: center;
      border-radius: 0.2rem;
      margin-left: 0.5rem;
      transition: 0.5s;
      line-height: 2.3rem;
    }
    .btn-active {
      background: #409eff;
    }
  }
}
</style>
  1. 然后npm run dev,就可以實(shí)現(xiàn)局域網(wǎng)聊天了,有無(wú)線的話可以用手機(jī)連著無(wú)線訪問(wèn)你的IP地址訪問(wèn),沒(méi)的話可以試下多開幾個(gè)窗口,也是能看到效果的?。?/li>
  2. 進(jìn)入聊天室時(shí)和發(fā)送信息時(shí)服務(wù)器的打印日志

在這里插入圖片描述

到此這篇關(guān)于vue使用WebSocket模擬實(shí)現(xiàn)聊天功能的文章就介紹到這了,更多相關(guān)vue使用WebSocket實(shí)現(xiàn)聊天內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Vue3中el-table表格數(shù)據(jù)不顯示的原因和解決方法

    Vue3中el-table表格數(shù)據(jù)不顯示的原因和解決方法

    這篇文章主要給大家介紹了Vue3中el-table表格數(shù)據(jù)不顯示的原因和解決方法,文中有詳細(xì)的代碼示例供大家參考,如果有遇到相同問(wèn)題的朋友可以參考閱讀本文,希望能夠幫到您
    2023-11-11
  • Vue項(xiàng)目?jī)?yōu)化打包詳解

    Vue項(xiàng)目?jī)?yōu)化打包詳解

    這篇文章主要為大家介紹了Vue項(xiàng)目的優(yōu)化打包,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2021-11-11
  • vue鼠標(biāo)懸停事件監(jiān)聽實(shí)現(xiàn)方法

    vue鼠標(biāo)懸停事件監(jiān)聽實(shí)現(xiàn)方法

    頁(yè)面在鼠標(biāo)懸停(不動(dòng))n秒之后,頁(yè)面進(jìn)行相應(yīng)的事件,下面這篇文章主要給大家介紹了關(guān)于vue鼠標(biāo)懸停事件監(jiān)聽的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09
  • vue虛擬化列表封裝的實(shí)現(xiàn)

    vue虛擬化列表封裝的實(shí)現(xiàn)

    這篇文章主要介紹了vue實(shí)現(xiàn)虛擬化列表封裝方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • Vue項(xiàng)目如何根據(jù)圖片url獲取file對(duì)象并用axios上傳

    Vue項(xiàng)目如何根據(jù)圖片url獲取file對(duì)象并用axios上傳

    這篇文章主要介紹了Vue項(xiàng)目如何根據(jù)圖片url獲取file對(duì)象并用axios上傳問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 淺談Vue CLI 3結(jié)合Lerna進(jìn)行UI框架設(shè)計(jì)

    淺談Vue CLI 3結(jié)合Lerna進(jìn)行UI框架設(shè)計(jì)

    這篇文章主要介紹了淺談Vue CLI 3結(jié)合Lerna進(jìn)行UI框架設(shè)計(jì),在此之前先簡(jiǎn)單介紹一下Element的構(gòu)建流程,以便對(duì)比新的UI框架設(shè)計(jì)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-04-04
  • 在vue中,v-for的索引index在html中的使用方法

    在vue中,v-for的索引index在html中的使用方法

    下面小編就為大家分享一篇在vue中,v-for的索引index在html中的使用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03
  • vue中的v-model原理,與組件自定義v-model詳解

    vue中的v-model原理,與組件自定義v-model詳解

    這篇文章主要介紹了vue中的v-model原理,與組件自定義v-model詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-08-08
  • 解決vue-cli輸入命令vue ui沒(méi)效果的問(wèn)題

    解決vue-cli輸入命令vue ui沒(méi)效果的問(wèn)題

    這篇文章主要介紹了解決vue-cli輸入命令vue ui沒(méi)效果的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-11-11
  • Vue二次封裝axios為插件使用詳解

    Vue二次封裝axios為插件使用詳解

    這篇文章主要介紹了Vue二次封裝axios為插件使用詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05

最新評(píng)論