vue使用websocket模拟实现聊天功能-简易版(代码片段)

程程0221 程程0221     2022-12-17     363

关键词:

vue使用WebSocket模拟实现聊天功能-简易版

效果展示 两个浏览器相互模拟

1.创建模拟node服务

在vue根目录下创建 server.js 文件模拟后端服务器

**在server终端目录下载 **

npm install --s ws

2.编写server.js文件

代码如下

var userNum = 0; //统计在线人数
var chatList = [];//记录聊天记录
var WebSocketServer = require('ws').Server;
wss = new WebSocketServer( port: 8181 ); //8181 与前端相对应
//调用 broadcast 广播,实现数据互通和实时更新
wss.broadcast = function (msg) 
    wss.clients.forEach(function each(client) 
        client.send(msg);
    );
;
wss.on('connection', function (ws) 
    userNum++;//建立连接成功在线人数 +1
    wss.broadcast(JSON.stringify( funName: 'userCount', users: userNum, chat: chatList )); //建立连接成功广播一次当前在线人数
    console.log('Connected clients:', userNum);
    //接收前端发送过来的数据
    ws.on('message', function (e) 
        var resData = JSON.parse(e)
        console.log('接收到来自clent的消息:' + resData.msg)
        chatList.push( userId: resData.userId, content: resData.msg );//每次发送信息,都会把信息存起来,然后通过广播传递出去,这样此每次进来的用户就能看到之前的数据
        wss.broadcast(JSON.stringify( userId: resData.userId, msg: resData.msg )); //每次发送都相当于广播一次消息

    );
    ws.on('close', function (e) 
        userNum--;//建立连接关闭在线人数 -1
        wss.broadcast(JSON.stringify( funName: 'userCount', users: userNum, chat: chatList ));//建立连接关闭广播一次当前在线人数
        console.log('Connected clients:', userNum);
        console.log('长连接已关闭')
    )
)
console.log('服务器创建成功')

然后npm run start启动服务器

3.vue前端页面

代码如下

<template>
  <div class="chat-box">
    <header>聊天室人数: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()">发送</div>
    </div>
  </div>
</template>
 
<script>
export default 
  data() 
    return 
      ws: null,
      count: 0,
      userId: null, //当前用户ID
      list: [], //聊天记录的数组
      contentText: "", //input输入的值
    ;
  ,
  created() 
    this.getUserID();
  ,
  mounted() 
    this.initWebSocket();
  ,
  methods: 
    //根据时间戳作为当前用户ID
    getUserID() 
      let time = new Date().getTime();
      this.userId = time;
    ,
    //根据userID生成一个随机头像
    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));
      
    ,
    //滚动条到底部
    scrollBottm() 
      let el = this.$refs["msg-box"];
      el.scrollTop = el.scrollHeight;
    ,
    //发送聊天信息
    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)); //调用WebSocket send()发送信息的方法
      _this.contentText = "";
      setTimeout(() => 
        _this.scrollBottm();
      , 500);
    ,
    //进入页面创建websocket连接
    initWebSocket() 
      let _this = this;
      //判断页面有没有存在websocket连接
      if (window.WebSocket) 
        // 此处的 :8181 端口号 要与后端配置的一致
        let ws = new WebSocket("ws://192.168.5.42:9502"); 
        // let ws = new WebSocket("ws://192.168.5.8:8181"); //这里是我本地测试
        _this.ws = ws;
        ws.onopen = function (e) 
          console.log("服务器连接成功");
        ;
        ws.onclose = function (e) 
          console.log("服务器连接关闭");
        ;
        ws.onerror = function () 
          console.log("服务器连接出错");
        ;
        ws.onmessage = function (e) 
          //接收服务器返回的数据
          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,就可以实现局域网聊天了,有无线的话可以用手机连着无线访问你的IP地址访问,没的话可以试下多开几个窗口,也是能看到效果的!!
  2. 进入聊天室时和发送信息时服务器的打印日志

使用html5下websocket搭建简易聊天室

一、Html5WebSocket介绍WebSocketprotocol是HTML5一种新的协议(protocol)。它是实现了浏览器与服务器全双工通信(full-duplex)。现在,很多网站为了实现即时通讯(real-time),所用的技术都是轮询(polling)。轮询是在特定的的时间间隔(timeinterval)(... 查看详情

vue+websocket<简单实现聊天功能>(代码片段)

效果图:聊天室此篇文章是针对Websocket的简单了解和应用,利用Nodejs简单搭建一个服务器加以实现。首先创建一个vue项目然后再创建一个server文件夹,在终端上打开该文件夹,输入vueinit(一直敲"回车"键... 查看详情

spring-websocket实现简易在线聊天(代码片段)

引入spring-websocket包<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>$websocket.ver 查看详情

springboot+websocket实现简易聊天室

①:什么是WebSocket??WebSocket是一种在单个TCP连接上进行全双工通信的协议?根据这个定义有两个注意的地方:1.什么是协议??协议就是相互通信的计算机双方必须共同遵守的一组约定。2.WebSocket协议和HTTP协议的区别??1)HTTP协议... 查看详情

ssh项目中使用websocket实现网页聊天功能

参考文章 :java使用websocket,并且获取HttpSession,源码分析  http://www.cnblogs.com/zhuxiaojie/p/6238826.html 1.在项目中引入依赖websocket遵循了javaee规范,所以需要引入javaee的包1<dependency>2<groupId>javax.w 查看详情

swoole用websocket服务器搭建一个简易的聊天室功能(代码片段)

swoole用WebSocket服务器搭建一个简易的聊天室功能域名无ssl加密域名有ssl加密开启服务端常链接浏览器分别开启两个客户端窗口,进行聊天域名无ssl加密WS.php写服务端代码<?phpclassWSprivate$ws=null;publicfunction__construct()//创建Web... 查看详情

swoole用websocket服务器搭建一个简易的聊天室功能(代码片段)

swoole用WebSocket服务器搭建一个简易的聊天室功能域名无ssl加密域名有ssl加密开启服务端常链接浏览器分别开启两个客户端窗口,进行聊天域名无ssl加密WS.php写服务端代码<?phpclassWSprivate$ws=null;publicfunction__construct()//创建Web... 查看详情

android使用websocket实现即时通讯功能,聊天功能

...不愿意花这份钱),那就得自己做了,所以我们需要使用WebSocket。一.Android实现即时通讯功能1.引入WebSock依赖2.创建一个java类并继承WebSocketClient其中onOpen()方法在websocket连接开启时调用,onMessage()方法在接收到消息时调用,onClose()... 查看详情

java是如何实现客服在线聊天功能的?

...候,需要考虑客户端和服务端之间的通信协议。可以使用WebSocket协议,这是一种全双工通信协议,支持客户端和服务端之间的实时通信。Java提供了多个WebSocket实现,比如Tyrus、Jetty和Netty。实现服务端:在服务端实现在线聊天功... 查看详情

使用websocket实现网页聊天室(代码片段)

使用WebSocket实现网页聊天室一、文章导读服务器推送你还在使用轮询吗?本文将带你领略WebSocket的魅力,轻松实现服务器推送功能。本文将以下面两方面让你理解WebSocket并应用到具体的开发中WebSocket概述使用WebSocket实现... 查看详情

使用 php 在 android 中使用 websocket 实现聊天

】使用php在android中使用websocket实现聊天【英文标题】:Implementchatusingwebsocketinandroidwithphp【发布时间】:2014-08-1705:55:04【问题描述】:我想通过php在android中使用websocket实现聊天功能。我需要同样的php代码。场景是这样的。android... 查看详情

nodejs构建多房间简易聊天室

...务器端搭建  本服务器需要提供两个功能:http服务和websocket服务,由于node的事件驱动机制,可将两种服务搭建在同一个端口下。  1、包描述文件:package.json,这里用到了两个依赖项,mime:确定静态文件mime类型,socket.io:搭... 查看详情

ws模块指南+vue在线聊天室(代码片段)

简介ws模块是Node端的一个WebSocket协议的实现,该协议允许客户端(一般是浏览器)持久化和服务端的连接.这种可以持续连接的特性使得WebScoket特别适合用于适合用于游戏或者聊天室等使用场景.ws模块相较于其他基于WebSocket协议的模... 查看详情

springboot+websocket+vue+vuex实现在线聊天(客户端)(代码片段)

一、使用node代理ws请求proxyObj['/ws']=ws:true,target:"ws://localhost:8081"导入连接需要连接websocket的js npminstallsockjs-clientnpminstallstompjsnpminstallsass-loader@8.0.2--save//这个是css写法需要用到 查看详情

laravel+swoole打造im简易聊天室(代码片段)

...用场景:实现简单的即时消息聊天室(一)扩展安装(二)webSocket服务端代码(三)客户端实现应用场景:实现简单的即时消息聊天室(一)扩展安装peclinstallswoole安装完成后可以通过以下命令检测Swoole是否安装成功php-m|grepswoole(二)w... 查看详情

laravel+swoole打造im简易聊天室(代码片段)

...用场景:实现简单的即时消息聊天室(一)扩展安装(二)webSocket服务端代码(三)客户端实现应用场景:实现简单的即时消息聊天室(一)扩展安装peclinstallswoole安装完成后可以通过以下命令检测Swoole是否安装成功php-m|grepswoole(二)w... 查看详情

html5-websocket的应用之简易聊天室

 需要知识点:前端知识jq操作domnodejssocket.io 关于websocketapi的知识点,见上篇章《HTML5-Websocket》。 聊天室思路/原理:A和B聊天:A发送消息到中间“聊天服务器”,服务器发送消息给BB接收A的消息,实现第一次消... 查看详情

使用activemq实现简易聊天功能(代码片段)

...可以把消息队列比作是一个存放消息的容器,当我们需要使用消息的时候可以取出消息供自己使用。消息队列是分布式系统中重要的组件,使用消息队列主要是为了通过异步处理提高系统性能和削峰、降低系统耦合性。目前使用... 查看详情