vue signal实现前后端实时消息同步

版权声明:本文为博主原创文章,转载请注明出处:http://blog.csdn.net/deaidai https://blog.csdn.net/deaidai/article/details/82914413

##前言
最近接了一个项目,要求用websocket连接,结果来了一个.Net的signal,我负责处理前端,拿到后端给的样例js后,开始着手写vue这端的连接。
主要目的是实现服务器向用户发送消息,用户向服务器发送消息完全可以post请求即可。
如何入手,请先看这个链接<<
##在Vue项目中使用SignalR
首先安装 SignalR 的package,需要注意的是 SignalR 依赖 jQuery。
npm i signalr jquery --save
为了方便,在webpack.base.conf.js中注册全局的jQuery
var webpack = require('webpack')

plugins: [new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'root.jQuery': 'jquery'
        })
    ]

然后在main.js中引入 SignalR
import 'signalr'
##我的样例demo.vue
注意连接的地址,是后端给的,需要和后端沟通,还有“PlatHub”名字也需要和后端沟通,接收消息的方法ReceiveMsg也要和后端沟通,再就是AJAX其实不是SignalR了,一定要注意,conn.start().done((data) => {}))成功后才能表示SignalR连接成功

<template>
    <div>
        signalr connect
        <div>
            <div>{{showmsg}}</div>
            <input v-model="value" placeholder="请输入..." />
            <Button type="info" @click="sendMsg">信息按钮</Button>
        </div>
    </div>
    </template>
    <script>
    import signalR from 'signalr'
    export default {
      name: "Signalr",
      data() {
          return {
              value: "",
              showmsg: "",
              proxy: {}
          }
      },
      mounted() {
          this.connectServer();
      },
      methods: {
        connectServer() {
            var $this = this;
            var conn = $.hubConnection("https://demo.xxtxb.cn/signalr", { useDefaultPath: false })
            $this.proxy = conn.createHubProxy("PlatHub");
            $this.proxy.on("ReceiveMsg", (data) => {
                $this.showmsg = data;
                console.log('demo ReceiveMsg:', data)
            })
            conn.start().done((data) => {
                $this.sendMsg()
            }).fail((data) => {
              console.log('conn fail')
            });
        },
        sendMsg() {
          var $this = this;
          $.ajax({
              url: 'https://demo.xxtxb.cn/r/RadarError/ToSingle',
              type: 'POST', //GET
              async: true,    //或false,是否异步
              data: {
                  client: 123,
                  msg: $this.value
              },
              timeout: 5000,    //超时时间
              dataType: 'json',    //返回的数据格式:json/xml/html/script/jsonp/text
              success: function (data, textStatus, jqXHR) {
                  if (data.code == 1) {
                      console.log('发送成功')
                  }
                  else
                      console.log("对方不在线");
              },
              error: function (xhr, textStatus) {
                  console.log('错误')
                  console.log(xhr)
                  console.log(textStatus)
              }
          })
        }
      }
    }
    </script>

    <style>

    </style>

猜你喜欢

转载自blog.csdn.net/deaidai/article/details/82914413
今日推荐