前端使用vue和elementui通过websocket连接后端,使用reconnecting-websocket.min.js封装类保证断线重连。
loginMore.vue
<template>
<el-form :model="form">
<el-form-item label="用户名称">
<el-input v-model="form.others[0]"></el-input>
</el-form-item>
<el-form-item label="账号">
<el-input v-model="form.account"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="form.password"></el-input>
</el-form-item>
<el-form-item label="群聊名称">
<el-input v-model="form.chatName"></el-input>
</el-form-item>
<el-form-item label="传递给的用户">
<el-input v-model="form.others[1]"></el-input>
</el-form-item>
<el-form-item label="传递给的用户">
<el-input v-model="form.others[2]"></el-input>
</el-form-item>
<el-form-item label="传递给的用户">
<el-input v-model="form.others[3]"></el-input>
</el-form-item>
<el-button type="primary" @click="onSubmit">登录</el-button>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {
id: '',
account: '',
password: '',
others: [],
chatName:''
}
}
}, methods: {
onSubmit() {
// 向具有指定ID的用户发出请求
let data = new FormData();
data.append('id',this.form.others[0])
data.append('account',this.form.account)
data.append('password',this.form.password)
data.append('others',this.form.others)
data.append("chatName",this.form.chatName)
this.axios.post('http://localhost:8081/login',data)
.then(function (response) {
this.$router.push({ name: 'webSocketMore',params:{token: response.data,id:this.form.others[0]}})
}.bind(this))
.catch(function (error) {
console.log(error)
})
}
}
}
</script>
<style scoped>
</style>
webSocketMore.vue
<template>
<el-row>
<el-col style="width: 100%;height: 300px;border: 1px #909090 solid;" >
<span v-model="name">{{name}}</span>
<div v-for="data in receiveData" v-bind:class="receiveData">
<div v-if="data.position==='right'" style="margin-right: 10px;text-align: right" >{{data.msg}}</div>
<div v-if="data.position==='left'" style="margin-left: 10px;text-align: left">{{data.msg}}</div>
</div>
</el-col>
<el-col>
<el-input type="textarea" placeholder="请输入内容" v-model="sendData" show-word-limit :rows="10">
</el-input>
</el-col>
<el-col style="text-align: right">
<el-button type="primary" plain @click="send">提交数据</el-button>
</el-col>
</el-row>
</template>
<script>
import ReconnectingWebSocket from '../js/reconnecting-websocket.min.js'
export default {
data() {
return {
websocket: null,
sendData: '',
receiveData: [
{name:'',position:''}
],
name:'',
chatGroupId:'',
data:''
}
},
mounted() {
if ('WebSocket' in window) {
//使用ReconnectingWebSocket增加断线重连机制
this.websocket = new ReconnectingWebSocket('ws://localhost:8082/ws')
this.initWebSocket()
} else {
alert('当前浏览器 Not support websocket')
}
},
beforeDestroy() {
this.onbeforeunload()
},
methods: {
initWebSocket() {
//连接错误
this.websocket.onerror = this.setErrorMessage
// //连接成功
this.websocket.onopen = this.setOnopenMessage
//收到消息的回调
this.websocket.onmessage = this.setOnmessageMessage
//连接关闭的回调
this.websocket.onclose = this.setOncloseMessage
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = this.onbeforeunload
},
setErrorMessage() {
// this.receiveData = "WebSocket连接发生错误" + ' 状态码:' + this.websocket.readyState;
},
setOnopenMessage() {
//登录成功后向后端发送信息发送数据
//目前是创建群聊
let data={"token":this.$route.params.token,"chatType":'more'}
data = JSON.stringify(data);
this.websocket.send(data)
// this.receiveData = "WebSocket连接成功" + ' 状态码:' + this.websocket.readyState;
},
//回调消息
setOnmessageMessage(event) {
this.data=event.data
let data = JSON.parse(event.data);
if (data.chatGroupId!=null){
this.chatGroupId=data.chatGroupId;
}
if (data.msg!=null){
var name='';
if (data.userId==='1'){
name='星星'
}else if (data.userId==='2'){
name='小亮'
} else if (data.userId==='3'){
name='小乔'
}else if (data.userId==='4') {
name='许BB'
}
console.log(name)
if (data.userId===this.$route.params.id) {
this.receiveData.push({"msg":name+":"+data.msg,"position":"right"})
}else{
this.receiveData.push({"msg":name+":"+data.msg,"position":"left"})
}
}
},
setOncloseMessage() {
// this.receiveData = "WebSocket连接关闭" + ' 状态码:' + this.websocket.readyState;
},
onbeforeunload() {
this.closeWebSocket();
},
//websocket发送消息
send() {
let data={"token":this.$route.params.token,"msg":this.sendData,"chatType":'more',chatGroupId:"9cf8e1bc-26b9-4157-bcd6-139e76703196"}
data = JSON.stringify(data);
this.websocket.send(data)
this.sendData = ''
},
closeWebSocket() {
this.websocket.close()
}
}
}
</script>
<style>
.content {
width: 100%;
height: 90%;
border: 1px black solid;
}
.el-textarea__inner {
width: 100%;
}
</style>
最终实现效果:
代码已上传至github:https://github.com/beibeirenzhe/netty-im/tree/master/fyrtwebsocketim