代码如下:
<!DOCTYPE html>
<html>
<head>
<title>webstock 测试工具</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<style>
button {
padding: 4px 8px;
background-color: #0f1f2a;
color: #fff;
outline: none;
border: none;
border-radius: 4px;
cursor: pointer;
}
input {
padding: 4px 8px;
}
label {
font-size: 14px;
}
</style>
</head>
<body>
<div id="app">
<h3>{{title}}</h3>
<p>
<label>webstock URL</label>
<input v-model="webstockUrl" placeholder="请输入ws地址" />
</p>
<p>
<button @click="handleConnect" v-if="!websocket">开始连接</button>
<button @click="handleClose" v-if="websocket">断开连接</button>
</p>
<h3>webstock 连接状态</h3>
<p v-if="websocket">
<label v-if="webstockStatus===0">正在链接中</label>
<label v-if="webstockStatus===1">已经链接并且可以通讯</label>
<label v-if="webstockStatus===2">连接正在关闭</label>
<label v-if="webstockStatus===3">连接已关闭或者没有链接成功</label>
</p>
<h3>发送消息</h3>
<p>
<label>消息内容</label>
<input v-model="sendInfo" placeholder="请输入要发送的消息内容" />
<button @click="handleSendInfo(sendInfo)">发送</button>
</p>
<h3>收到的消息</h3>
<p v-for="(message,index) in messageList" :key="index">{{message.data}}</p>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
title: 'webstock 测试工具',
websocket: null,
webstockUrl: '',
webstockStatus: 0,
sendInfo: '',
messageList: [],
},
methods: {
// 建立连接
handleConnect() {
// 初始化,清空消息队列
this.messageList = [];
// 新建一个连接
this.websocket = new WebSocket(this.webstockUrl);
// 处理收到消息
this.websocket.onopen = (event) => {
console.log(event);
this.webstockStatus = 1;
};// 处理收到消息
this.websocket.onmessage = (message) => {
console.log(message);
this.messageList.push(message);
};
// 处理错误
this.websocket.onerror = (error) => {
this.webstockStatus = 3;
alert(JSON.stringify(error));
};
// 关闭连接
this.websocket.onclose = (error) => {
this.webstockStatus = 2;
};
},
// 发送消息
handleSendInfo(data) {
if (this.websocket.readyState === 1) {
this.websocket.send(JSON.stringify(data));
}
},
// 断开连接
handleClose() {
this.websocket.close();
}
},
})
</script>
</body>
</html>
- 效果图
- 先输入相应的数据并点击开始连接
2, 连接成功以后,就可以发送消息或者等待接收消息了