简体   繁体   中英

Unable to connect to WebSocket with Vue plugin

I'd like to write a vue-plugin to get handy WebSocket methods like connect() and subscribe() in my Vue application. I've got a problem with connecting to WebSocket, it only works when I call connect() method in the mounted hook and load the whole page (like with the browser refresh button). In another case, when I first load the page and then call the connect() method explicitly by the button click, the connection isn't established.

My vue-plugin code:

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;

My vue component:

<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>

In the case, I uncomment the mounted hook, after page load I see the console log like this:

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: ""}

And everything works correct. But, if I comment the mounted hook and want to connect with the WebSocket by the button click, the console log looks like this:

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

and that's it, the connection isn't established. Why this happens and how to fix it?

OK I figured it out. The problem line was const stompClient = getStompClient("http://localhost:8080/ws"); in the plugin. I've moved it to the connect method and store as 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 => {

Later, I use ws.stompClient and it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM