spring boot netty整合websocket 即时通讯系统之用户群聊(十一)

前端使用vue和elementui通过websocket连接后端,使用reconnecting-websocket.min.js封装类保证断线重连。

loginMore.vue

<template>
  <el-form :model="form">
    <el-form-item label="用户名称">
      <el-input v-model="form.others[0]"></el-input>
    </el-form-item>
    <el-form-item label="账号">
      <el-input v-model="form.account"></el-input>
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="form.password"></el-input>
    </el-form-item>
    <el-form-item label="群聊名称">
      <el-input v-model="form.chatName"></el-input>
    </el-form-item>
    <el-form-item label="传递给的用户">
      <el-input v-model="form.others[1]"></el-input>
    </el-form-item>
    <el-form-item label="传递给的用户">
      <el-input v-model="form.others[2]"></el-input>
    </el-form-item>
    <el-form-item label="传递给的用户">
      <el-input v-model="form.others[3]"></el-input>
    </el-form-item>
    <el-button type="primary" @click="onSubmit">登录</el-button>
  </el-form>
</template>

<script>
  export default {
    data() {
      return {
        form: {
          id: '',
          account: '',
          password: '',
          others: [],
          chatName:''
        }
      }
    }, methods: {
      onSubmit() {
// 向具有指定ID的用户发出请求
        let data = new FormData();
        data.append('id',this.form.others[0])
        data.append('account',this.form.account)
        data.append('password',this.form.password)
        data.append('others',this.form.others)
        data.append("chatName",this.form.chatName)
        this.axios.post('http://localhost:8081/login',data)
          .then(function (response) {
            this.$router.push({ name: 'webSocketMore',params:{token: response.data,id:this.form.others[0]}})
          }.bind(this))
          .catch(function (error) {
            console.log(error)
          })
      }
    }
  }
</script>

<style scoped>

</style>

webSocketMore.vue

<template>
  <el-row>
    <el-col style="width: 100%;height: 300px;border: 1px #909090 solid;" >
      <span v-model="name">{{name}}</span>
      <div v-for="data in receiveData" v-bind:class="receiveData">
        <div v-if="data.position==='right'"  style="margin-right: 10px;text-align: right" >{{data.msg}}</div>
        <div  v-if="data.position==='left'" style="margin-left: 10px;text-align: left">{{data.msg}}</div>
      </div>
    </el-col>
    <el-col>
      <el-input type="textarea" placeholder="请输入内容" v-model="sendData" show-word-limit :rows="10">
      </el-input>
    </el-col>
    <el-col style="text-align: right">
      <el-button type="primary" plain @click="send">提交数据</el-button>
    </el-col>
  </el-row>
</template>
<script>
  import ReconnectingWebSocket  from '../js/reconnecting-websocket.min.js'
  export default {
    data() {
      return {
        websocket: null,
        sendData: '',
        receiveData: [
          {name:'',position:''}
          ],
        name:'',
        chatGroupId:'',
        data:''
      }
    },
    mounted() {
      if ('WebSocket' in window) {
        //使用ReconnectingWebSocket增加断线重连机制
        this.websocket = new ReconnectingWebSocket('ws://localhost:8082/ws')
        this.initWebSocket()
      } else {
        alert('当前浏览器 Not support websocket')
      }
    },
    beforeDestroy() {
      this.onbeforeunload()
    },
    methods: {
      initWebSocket() {
        //连接错误
        this.websocket.onerror = this.setErrorMessage

        // //连接成功
        this.websocket.onopen = this.setOnopenMessage

        //收到消息的回调
        this.websocket.onmessage = this.setOnmessageMessage

        //连接关闭的回调
        this.websocket.onclose = this.setOncloseMessage

        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = this.onbeforeunload
      },
      setErrorMessage() {
        // this.receiveData = "WebSocket连接发生错误" + '   状态码:' + this.websocket.readyState;
      },
      setOnopenMessage() {
        //登录成功后向后端发送信息发送数据
        //目前是创建群聊
        let data={"token":this.$route.params.token,"chatType":'more'}
        data = JSON.stringify(data);
        this.websocket.send(data)
        // this.receiveData = "WebSocket连接成功" + '   状态码:' + this.websocket.readyState;
      },
      //回调消息
      setOnmessageMessage(event) {
        this.data=event.data
        let data = JSON.parse(event.data);

        if (data.chatGroupId!=null){
          this.chatGroupId=data.chatGroupId;
        }
       if (data.msg!=null){
         var name='';
         if (data.userId==='1'){
           name='星星'
         }else if (data.userId==='2'){
           name='小亮'
         } else if (data.userId==='3'){
           name='小乔'
         }else if (data.userId==='4') {
           name='许BB'
         }
         console.log(name)
        if (data.userId===this.$route.params.id) {
          this.receiveData.push({"msg":name+":"+data.msg,"position":"right"})
        }else{
          this.receiveData.push({"msg":name+":"+data.msg,"position":"left"})
        }
        }

      },
      setOncloseMessage() {
        // this.receiveData = "WebSocket连接关闭" + '   状态码:' + this.websocket.readyState;
      },
      onbeforeunload() {
        this.closeWebSocket();
      },
      //websocket发送消息
      send() {
        let data={"token":this.$route.params.token,"msg":this.sendData,"chatType":'more',chatGroupId:"9cf8e1bc-26b9-4157-bcd6-139e76703196"}
         data = JSON.stringify(data);
        this.websocket.send(data)
        this.sendData = ''
      },
      closeWebSocket() {
        this.websocket.close()
      }
    }
  }
</script>

<style>

  .content {
    width: 100%;
    height: 90%;
    border: 1px black solid;
  }

  .el-textarea__inner {
    width: 100%;
  }
</style>

 

最终实现效果:

  

代码已上传至github:https://github.com/beibeirenzhe/netty-im/tree/master/fyrtwebsocketim  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值