<template>
<div class="app-container">
<el-input
placeholder="请选择日期"
suffix-icon="el-icon-edit-outline"
v-model="messagedata"
style="width: 400px; margin: 0 10px"
>
</el-input>
<el-button type="primary" @click="init">建立连接</el-button>
<el-button type="success" @click="send">发送信息</el-button>
<el-button type="info" @click="close">断开连接</el-button>
</div>
</template>
<script>
// import { getToken } from '@/utils/auth'
export default {
data() {
return {
url: "ws://192.168.1.17:11111/websocket",
ws: null,
// 推送消息
messagedata: "",
};
},
created() {},
mounted() {},
methods: {
init() {
if (typeof WebSocket === "undefined") {
this.$modal.msgError("您的浏览器不支持WebSocket");
return;
} else {
this.$modal.msgSuccess("WebSocket loading...");
// const token = getToken();
// console.log({token});
// 实例化socket
this.ws = new WebSocket(this.url);
// 监听socket连接
this.ws.onopen = this.open;
// 监听socket错误信息
this.ws.onerror = this.error;
// 监听socket消息
this.ws.onmessage = this.getMessage;
}
},
// websocket建立连接
open() {
console.log("socket连接成功");
},
// websocket错误信息
error() {
console.log("连接错误");
},
// 接受后端消息
getMessage(msg) {
console.log(msg.data);
},
// 向后端发送信息
send() {
console.log("this.ws", this.ws);
this.ws.send(this.messagedata);
// const token = getToken();
// this.ws.send(JSON.stringify({
// type: 'authorization',
// token: token,
// }));
},
// 关闭websocket连接
close() {
if (this.ws) {
this.ws.close();
this.ws = null;
console.log("socket已经关闭");
}
},
},
destroyed() {
this.close();
},
};
</script>
<style lang="scss" scoped>
</style>
WebSocket简单例子
最新推荐文章于 2024-06-24 09:18:51 发布