<template>
<div>
<input v-model="txt"/>
<button @click="send">发送消息</button>
<input v-model="receivedMessage"/>
</div>
</template>
<script>
export default {
data () {
return {
path:"ws://localhost:8083/webSocket",
socket:"",
txt:"",
receivedMessage:""
}
},
mounted () {
// 初始化
this.init()
},
methods: {
init: function () {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持WebSocket!")
}else{
//
this.socket = new WebSocket(this.path)
//
this.socket.onopen = this.open
//
this.socket.onerror = this.error
//
this.socket.onmessage = this.getMessage
}
},
open: function () {
console.log("WebSocket连接成功")
},
error: function () {
console.log("WebSocket错误")
},
getMessage: function (msg) {
this.receivedMessage=msg.data;
},
send: function () {
this.socket.send(this.txt)
},
close: function () {
console.log("WebSocket已关闭")
}
},
destroyed () {
//
this.socket.onclose = this.close
}
}
</script>
<style>
</style>
11-09
1189
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-20
791
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-14
2703
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-01
5886
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)