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

Vue+Websocket簡(jiǎn)單實(shí)現(xiàn)聊天功能

 更新時(shí)間:2021年08月31日 12:06:29   作者:水香木魚  
這篇文章主要為大家詳細(xì)介紹了Vue+Websocket簡(jiǎn)單實(shí)現(xiàn)聊天功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Vue+Websocket簡(jiǎn)單實(shí)現(xiàn)聊天功能的具體代碼,供大家參考,具體內(nèi)容如下

效果圖:

聊天室

此篇文章是針對(duì)Websocket的簡(jiǎn)單了解和應(yīng)用,利用Nodejs簡(jiǎn)單搭建一個(gè)服務(wù)器加以實(shí)現(xiàn)。

首先創(chuàng)建一個(gè)vue項(xiàng)目

然后再創(chuàng)建一個(gè)server文件夾,在終端上打開該文件夾,輸入vue init(一直敲 "回車" 鍵),最后再建一個(gè)server.js文件,如下圖

代碼如下:

server.js/

在server文件終端下 npm install --s ws

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ā)送過來的數(shù)據(jù)
    ws.on('message', function (e) {
        var resData = JSON.parse(e)
        console.log('接收到來自clent的消息:' + resData.msg)
        chatList.push({ userId: resData.userId, content: resData.msg });//每次發(fā)送信息,都會(huì)把信息存起來,然后通過廣播傳遞出去,這樣此每次進(jìn)來的用戶就能看到之前的數(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ù)器

HelloWorld.vue(前端頁面)

<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)入頁面創(chuàng)建websocket連接
    initWebSocket() {
      let _this = this;
      //判斷頁面有沒有存在websocket連接
      if (window.WebSocket) {
        // 192.168.0.115 是我本地IP地址 此處的 :8181 端口號(hào) 要與后端配置的一致
        let ws = new WebSocket("ws://192.168.0.115:8181");
        _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;
            console.log(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: 100%;
    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;
    }
    .btn-active {
      background: #409eff;
    }
  }
}
</style>

192.168.0.115是我本地的IP地址(默認(rèn)是 localhost ),你可以改成你自己的

然后npm run dev,就可以實(shí)現(xiàn)局域網(wǎng)聊天了,有無線的話可以用手機(jī)連著無線訪問你的IP地址訪問,🙃沒的話可以試下多開幾個(gè)窗口,也是能看到效果的?。?/p>

進(jìn)入聊天室時(shí)和發(fā)送信息時(shí)服務(wù)器的打印日志

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 聊聊Vue 中 title 的動(dòng)態(tài)修改問題

    聊聊Vue 中 title 的動(dòng)態(tài)修改問題

    這篇文章主要介紹了 Vue 中 title 的動(dòng)態(tài)修改問題,文中通過兩種方案給大家介紹了title的傳遞問題 ,需要的朋友可以參考下
    2019-06-06
  • Vue中provide、inject詳解以及使用教程

    Vue中provide、inject詳解以及使用教程

    provide和inject主要為高階插件/組件庫(kù)提供用例,并不推薦直接用于應(yīng)用程序代碼中,下面這篇文章主要給大家介紹了關(guān)于Vue中provide、inject詳解以及使用的相關(guān)資料,需要的朋友可以參考下
    2022-11-11
  • Vue項(xiàng)目部署上線全過程記錄(保姆級(jí)教程)

    Vue項(xiàng)目部署上線全過程記錄(保姆級(jí)教程)

    vue項(xiàng)目開發(fā)完畢后,我們需要將項(xiàng)目打包上線,同時(shí)我們希望可以在本地預(yù)覽生產(chǎn)環(huán)境項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于Vue項(xiàng)目部署上線的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • vue3的組件通信&v-model使用實(shí)例詳解

    vue3的組件通信&v-model使用實(shí)例詳解

    props 主要用于父組件向子組件通信,再父組件中通過使用:msg='msg'綁定需要傳給子組件的屬性值,然后再在子組件中用props接收該屬性值,這篇文章主要介紹了vue3的組件通信&v-model使用,需要的朋友可以參考下
    2024-05-05
  • 詳解Vue.js——60分鐘組件快速入門(上篇)

    詳解Vue.js——60分鐘組件快速入門(上篇)

    本篇文章主要介紹了Vue.js組件,組件系統(tǒng)是Vue.js其中一個(gè)重要的概念,具有一定的參考價(jià)值,有需要的可以了解一下。
    2016-12-12
  • vue實(shí)現(xiàn)鼠標(biāo)移入移出事件代碼實(shí)例

    vue實(shí)現(xiàn)鼠標(biāo)移入移出事件代碼實(shí)例

    這篇文章主要介紹了vue實(shí)現(xiàn)鼠標(biāo)移入移出事件,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Vue3 將組件手動(dòng)渲染到指定元素中的方法實(shí)現(xiàn)

    Vue3 將組件手動(dòng)渲染到指定元素中的方法實(shí)現(xiàn)

    本文主要介紹了Vue3 將組件手動(dòng)渲染到指定元素中的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • 基于Vue實(shí)現(xiàn)頁面切換左右滑動(dòng)效果

    基于Vue實(shí)現(xiàn)頁面切換左右滑動(dòng)效果

    這篇文章主要為大家詳細(xì)介紹了基于Vue實(shí)現(xiàn)頁面切換左右滑動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • 跟混亂的頁面彈窗說再見

    跟混亂的頁面彈窗說再見

    這篇文章主要介紹了跟混亂的頁面彈窗說再見,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • vue實(shí)現(xiàn)輪播圖的多種方式

    vue實(shí)現(xiàn)輪播圖的多種方式

    這篇文章給大家介紹了vue實(shí)現(xiàn)輪播圖的多種方式,文中給出了四種實(shí)現(xiàn)方式,并通過代碼示例給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,感興趣的朋友可以參考下
    2024-02-02

最新評(píng)論