vue的监听者模式+webstock的结合使用

服务端

首先新创建一个node的空项目,然后安装 npm install nodejs-websocket
在index.js里面编写下面的内容:

var ws = require("nodejs-websocket");
console.log("开始建立连接...")
var server = ws.createServer(function(conn){
    conn.on("text", function (str) {
        console.log("收到的信息为:"+str)
        conn.sendText(str)
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)

console.log("WebSocket建立完毕")

上面只是服务端跑起来一个webstock,为了方便后面的测试和演示,收到什么内容就回复什么内容


客户端

新建一个vue项目,在vue项目的入口文件 main.js编写以下内容

import Vue from 'vue'
import App from './App'
import {router} from './router/index'; //引入路由实例
import {webstock} from  './libs/webstock'

Vue.prototype.$webstock = webstock;
Vue.prototype.$eventHub=new Vue(); //注意这里的写法

export  const VueObj= new Vue({
  router,
  render: h => h(App)
}).$mount('#app-box')

webstock.js:


      import {VueObj} from '../main'
      export const webstock = new WebSocket("ws://192.168.1.119:8001");

      /**
       * webstock连接成功
       */
      webstock.onopen = function () {
        console.log("websocket open");
      /*  let obj = {"requestType": "login"}
        webstock.send(JSON.stringify(obj))*/
      }
      /**
       * webstock接收消息
       */
      webstock.onmessage = function (message) {
        //console.log(JSON.parse(message.data));
        //这里注册了一个A事件
        VueObj.$eventHub.$emit('A事件', JSON.parse(message.data))
      }
      /**
       * webstock关闭
       */
      webstock.onclose = function (event) {
        console.log("websocket close");
      }
      /**
       * webstock出错
       */
      webstock.onerror = function (event) {
        webstock.close(event);
        console.log("websocket error");
      }

./router/index (定义路由路径)

    {path: '/test', component: () => import('@/components/Test/test')},

test.vue

<template>
  <div>
        <p><input type="text" v-model="webstock_type"><button @click="sendMsg">测试webstock</button></p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        webstock_type:'A'
      }
    },
    created() {
      //监听A事件,如果只想监听一次可以用  $this.$eventHub.$once
      this.$eventHub.$on('A事件', (res)=>{          
              console.log('test.vue界面收到消息---',res);
      } )
    },
    beforeDestroy(){
          //如果组件没有缓存,记得离开组件前解除A事件的监听,
          //不然重新加载该组件会出现重复监听的情况,缓存组件可以用 <keep-alive>
           this.$eventHub.$off('A事件')
           console.log(123);
    },
    methods: {
      sendMsg:function () {
            //往服务端发送一个消息,服务端马上回复消息,从触发webstock的接收消息方法里面注册的A事件
            this.$webstock.send(JSON.stringify(this.webstock_type))
      }
    }
  }
</script>


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容