0
点赞
收藏
分享

微信扫一扫

vue: WebSocket客户端


<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>


举报

相关推荐

0 条评论