前端代码
<template>
<div style="margin: 150px auto; width: 500px;box-shadow: 0 0 20px #33333350; border-radius: 10px; padding: 20px;">
<h2>websocket学习学习</h2>
<h3>学海无涯,回头是岸</h3>
<div style="margin-top: 20px; text-align: left">
<input type="text" v-model="msg">
<button @click="websocketsend(msg)">发送</button>
<div v-if="bmsg">
<ul>
<li v-for="(item, i) in bmsg" :key="i">
<strong :class="{services:item.user==='服务器'}">{{item.user}}</strong>
回复时间:{{item.time}}
<div>
{{item.content}}
</div>
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'KolOnlineChat',
data() {
return {
websock: null,
msg: null,
bmsg: [],
}
},
mounted() {
this.initWebSocket()
},
destroyed() {
this.websock.close() // 离开路由断开websocket连接
},
methods: {
initWebSocket() { // 初始化websocket
const wsuri = "wss://localhost:9999/webSocketServer?userId=parker"
this.websock = new WebSocket(wsuri)
this.websock.onmessage = this.websocketonmessage
this.websock.onopen = this.websocketonopen
this.websock.onerror = this.websocketonerror
this.websock.onclose = this.websocketclose
},
websocketonopen() { //连接建立之后执行send方法发送数据
// let actions = {'test': '12345'}
// this.websocketsend(JSON.stringify(actions))
},
websocketonerror(){//连接建立失败重连
this.initWebSocket()
},
websocketonmessage(e){ //数据接收
const redata = JSON.stringify(e.data)
this.arrOpear(redata, 'services')
},
websocketsend(Data){//数据发送
this.websock.send(Data)
this.arrOpear(Data, 'localhost')
},
websocketclose(e){ //关闭
console.log('断开连接',e)
},
arrOpear(msg, type) {
let _b = {
content: msg,
user: type === 'services'? '服务器' : '我',
time: new Date().toLocaleTimeString()
}
this.bmsg.push(_b)
}
}
}
</script>
<style scoped lang="less">
strong {
color: #03be01;
}
strong.services {
color: orangered;
}
</style>
运行截图:
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于