后端主动向前端推送消息实现websocket

简介:
WebSocket是html5新增加的一种通信协议,目前流行的浏览器都支持这个协议,例如Chrome,Safrie,Firefox,Opera,IE等等

vue案例:

<template>
  <div>
    <table>
      <thead>
      <tr>
        <th>消息编号</th>
        <th>发送者</th>
        <th>发送时间</th>
        <th>发送内容</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="item in messageList" :key="item.time">
        <td>{{ item.id }}</td>
        <td>{{ item.username }}</td>
        <td>{{ new Date(item.time).toLocaleTimeString() }}</td>
        <td>{{ item.message }}</td>
      </tr>
      </tbody>
    </table>
    <input
        type="text"
        v-model="sendMessage"
        placeholder="请输入你要发送的消息">
    <button @click="handleSendButton()">发送</button>
    <button @click="handleLogoutButton()">退出</button>
  </div>
</template>

<script>

import {
  getUsername,
  removeUsername
} from "@/utils/username";

export default {
  name: "Home",
  data() {
    return {
      webSocketObject: null,
      username: '',
      messageList: [

      ],
      sendMessage: ''
    }
  },
  created() {
    //从localStorage中获得username
    this.username = getUsername()
    //如果username不存在返回到登录页面
    if (!this.username){
      this.$router.push({
        name: 'Login'
      })
    }
    //初始化WebSocket
    this.webSocketInit()
  },
  beforeDestroy() {
    this.webSocketObject.close();//在该组件销毁时关闭该连接以节约资源
  },
  methods: {
    webSocketInit(){
      const webSocketUrl = 'ws://59.202.48.***:10010/websocket/cs'+this.username
      this.webSocketObject = new WebSocket(webSocketUrl);
      this.webSocketObject.onopen = this.webSocketOnOpen  //与服务端连接打开
      this.webSocketObject.onmessage = this.webSocketOnMessage //来自服务端的消息
      this.webSocketObject.onerror = this.webSocketOnError //与服务端连接异常
      this.webSocketObject.onclose = this.webSocketOnClose //与服务端连接关闭
    },
    webSocketOnOpen(e){
      console.log('与服务端连接打开->',e)
    },
    webSocketOnMessage(e){
      console.log('来自服务端的消息->',e)
      const receiveMessage = JSON.parse(e.data);
      this.messageList.push(receiveMessage)
    },
    webSocketOnError(e){
      console.log('与服务端连接异常->',e)
    },
    webSocketOnClose(e){
      console.log('与服务端连接关闭->',e)
    },

    // 发送信息
    handleSendButton() {
      const username = this.username
      const message = this.sendMessage
      this.webSocketObject.send(JSON.stringify({
        id: 1,
        message,
        username,
        time: new Date().getTime()
      }))
      this.sendMessage = ''
    },

    // 退出
    handleLogoutButton(){
      removeUsername() //清除username然后断开连接
      this.webSocketObject.close();
      this.$router.push({
        name: 'Login'
      })
    }
  },
}
</script>

<style scoped>

</style>

如有需要,gitee可以搜索到相关的前后端项目demo。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值