<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
<!-- Import Element UI CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- Import Vue.js and Element UI -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<div>
<input v-model="url" type="text" style="width: 20%" />
<button @click="join" type="button">连接</button>
<button @click="exit" type="button">断开</button>
<br />
<textarea v-model="message" rows="9"></textarea>
<button @click="send" type="button">发送消息</button>
<br />
<br />
<textarea v-model="text_content" rows="9"></textarea> 返回内容
<br />
<br />
</div>
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
url: "ws://127.0.0.1:8080/webSocket",
message: "",
text_content: "",
ws: null,
};
},
methods: {
join() {
const wsuri = this.url;
this.ws = new WebSocket(wsuri);
const self = this;
this.ws.onopen = function (event) {
self.text_content = self.text_content + "已经打开连接!" + "\n";
};
this.ws.onmessage = function (event) {
self.text_content = event.data + "\n";
};
this.ws.onclose = function (event) {
self.text_content = self.text_content + "已经关闭连接!" + "\n";
};
},
exit() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
},
send() {
if (this.ws) {
this.ws.send(this.message);
} else {
alert("未连接到服务器");
}
},
},
});
</script>
</body>
</html>