我想编写一个vue插件来在我的Vue应用程序中获得方便的WebSocket方法,例如connect()
和subscribe()
。我在连接到WebSocket时遇到问题,它仅在我在已挂接的钩子中调用connect()
方法并加载整个页面时才起作用(例如使用浏览器刷新按钮)。在另一种情况下,当我第一次加载页面,然后通过单击按钮显式调用connect()
方法时,未建立连接。
我的Vue插件代码:
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>
在这种情况下,我取消注释已挂接的钩子,在页面加载后,我会看到这样的控制台日志:
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: ""}
一切正常。但是,如果我注释了已挂接的钩子并想通过单击按钮与WebSocket连接,则控制台日志如下所示:
websocket tester launched
connecting...
trying to connect websocket
Opening Web Socket...
就是这样,未建立连接。为什么会发生这种情况以及如何解决?
答案 0 :(得分:0)
好,我知道了。问题行是插件中的const stompClient = getStompClient("http://localhost:8080/ws");
。我已将其移至connect方法并存储为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
,效果很好。