Commit 9cc3abd5 by liuguorong93

websocket 连接测试

parent ed1952c8
export default {
listen(url, messageCallback, openCallback, closeCallback, errorCallback) {
if (typeof WebSocket === "undefined") {
console.log("您的浏览器不支持WebSocket");
return;
} else {
let protocol = "ws";
let newUrl = "";
if (window.location.protocol == "https:") {
protocol = "wss";
}
let env = process.env.NODE_ENV;
switch (env) {
case 'development':
newUrl = `${protocol}://47.92.48.137:4002/${url}`;
break;
case 'production':
newUrl = `${protocol}://${window.location.host}/${url}`;
break;
}
const ws = new WebSocket(newUrl);
ws.onopen = () => {
if (openCallback) openCallback();
};
ws.onclose = () => {
if (closeCallback) closeCallback();
};
ws.onerror = () => {
if (errorCallback) errorCallback();
};
ws.onmessage = (event) => {
try {
if (event?.data) {
const data = JSON.parse(event.data);
messageCallback(data);
}
} catch (e) {
console.log(e);
}
};
return ws;
}
},
};
...@@ -53,26 +53,47 @@ ...@@ -53,26 +53,47 @@
</template> </template>
<script> <script>
import websocket from "@/utils/websocket.js";
export default { export default {
data() { data() {
return {}; return {
ws: null,
};
},
beforeDestroy() {
this.closeWebSocket();
}, },
mounted() { mounted() {
// this.getLists(); // this.getLists();
// this.wsFn();
}, },
methods: { methods: {
getLists() { closeWebSocket() {
this.$nextTick(() => { if (this.ws && this.ws.readyState <= 1) this.ws.close();
jQuery(".messageClass").slide({ },
mainCell: ".infoListUl", wsFn() {
autoPage: true, let url = "ws/asset";
effect: "top", this.ws = websocket.listen(url, this.websocketCB, this.websocketErrCB);
autoPlay: true, },
scroll: 6, websocketCB(data) {
vis: 6, // console.log("data", data);
}); },
}); websocketErrCB(err) {
// console.log("err", err);
}, },
// getLists() {
// this.$nextTick(() => {
// jQuery(".messageClass").slide({
// mainCell: ".infoListUl",
// autoPage: true,
// effect: "top",
// autoPlay: true,
// scroll: 6,
// vis: 6,
// });
// });
// },
}, },
}; };
</script> </script>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment