javascript - 无法使用 Vue 插件连接到 WebSocket

标签 javascript vue.js websocket vuejs2 web-stomp

我想编写一个 vue 插件,以便在我的 Vue 应用程序中获取方便的 WebSocket 方法,例如 connect()subscribe()。我在连接到 WebSocket 时遇到问题,它仅在我调用已安​​装 Hook 中的 connect() 方法并加载整个页面时有效(就像使用浏览器刷新按钮一样)。在另一种情况下,当我首先加载页面然后通过单击按钮显式调用 connect() 方法时,未建立连接。

我的 vue-plugin 代码:

import SockJS from "sockjs-client";
import Stomp from "webstomp-client";

const WebSocketTester = {
  install(Vue, options) {
    console.log("websocket tester launched");
    let connected = false;
    const ws = {
      connected: () => connected
    };

    const stompClient = getStompClient("http://localhost:8080/ws");

    const connect = () => {
      return new Promise((resolve, reject) => {
        if (connected) {
          reject("Already connected !");
          return;
        }
        console.log("trying to connect websocket");
        stompClient.connect({}, frame => {
          console.log("got websocket frame:");
          console.log(frame);
          if (frame.command == "CONNECTED") {
            connected = true;
            resolve();
          } else {
            reject("Could not connect with " + url);
          }
        });
      });
    };

    ws.connect = () => {
      return connect();
    };

    Vue.prototype.$ws = ws;
  }
};

const getStompClient = webSocketUrl => {
  const socket = new SockJS(webSocketUrl);
  return Stomp.over(socket);
};

export default WebSocketTester;

我的 vue 组件:

<template>
  <div class="hello">
    <button @click="connect">Connect with websocket</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  methods: {
    connect() {
      console.log("connecting...");
      this.$ws.connect().catch(error => {
        console.log("could not connect by click");
        console.log(error);
      });
    }
  },
  mounted() {
    // this works well
    // this.$ws.connect().catch(error => {
    //   console.log("could not connect in mounted");
    //   console.log(error);
    // });
  }
};
</script>

在这种情况下,我取消注释挂载的钩子(Hook),在页面加载后我看到这样的控制台日志:

websocket tester launched
trying to connect websocket
Opening Web Socket...
Web Socket Opened...
DEPRECATED: undefined is not a recognized STOMP version. In next major client version, this will close the connection.
>>> CONNECT
>>> length 52
<<< CONNECTED
connected to server undefined
got websocket frame:
Frame {command: "CONNECTED", headers: {…}, body: ""}

一切正常。但是,如果我评论挂载的钩子(Hook)并想通过单击按钮连接到 WebSocket,则控制台日志如下所示:

websocket tester launched
connecting...
trying to connect websocket
Opening Web Socket...

就是这样,连接还没有建立。为什么会发生这种情况以及如何解决?

最佳答案

好吧,我明白了。问题行是插件中的 const stompClient = getStompClient("http://localhost:8080/ws");。我已将它移至连接方法并存储为 ws.object

        if (connected) {
          reject("Already connected !");
          return;
        }
        ws.stompClient = getStompClient("http://localhost:8080/ws");
        console.log("trying to connect websocket");
        ws.stompClient.connect({}, frame => {

后来,我使用了 ws.stompClient,它工作正常。

关于javascript - 无法使用 Vue 插件连接到 WebSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58302172/

相关文章:

javascript - 从ajax请求动态连接Vue中的数组不起作用

node.js - OpenShift 上的 WebSockets 不适用于远程客户端

javascript - ajax promise 数据未定义

javascript - 未添加要插入移动数据库的第一项

javascript - 我如何使用 jQuery 编写更短的代码?

java - Netty:如何限制每秒的Websocket channel 消息数?

php - 使用哪个 Ratchet 组件

javascript - 是否可以在某些 disqus 线程上将评论设为私有(private)?

webpack - 禁用 vue-cli webpack 编码图像 base64

javascript - Vuejs : Axios post JSON data and Image data