项目需要实现移动端的客服聊天界面,类似微信的聊天界面,需要做到实时通讯,所以使用了websocket
一、什么是websoket
- websoket是一种网络传输协议,位于OSI模型的应用层。可在单个TCP连接上进行全双工通信,能更好的节省服务器资源和带宽并达到实时通讯
- websoket可以建立服务器主动向客户端发送数据,实现双向连接通信,并且建立持久的通信
二、如何使用
mounted() {
this.initWebSocket();
}
methods:{
webchat_sendmsg(){
if(this.inputContent != '') {
const message = {
...
}
this.websocketSend(this.inputContent);
this.infoList.push(message);
console.log(this.infoList);
this.inputContent = ""
}
console.log('点击发送');
},
initWebSocket() {
let domianURL = 'ws://127.0.0.1/websoket/';
var url = domianURL+'需要拼接的参数';
console.log(url);
this.websock = new WebSocket(url);
this.websock.onopen = this.websocketOnopen;
this.websock.onerror = this.websocketOnerror;
this.websock.onmessage = this.websocketOnmessage;
this.websock.onclose = this.websocketOnclose;
},
websocketOnopen() {
console.log("WebSocket连接成功");
},
websocketOnerror(e) {
console.log("WebSocket连接发生错误",e);
},
websocketOnmessage(e) {
console.log('监听关闭' + e)
console.log("-----接收消息-------",e.data);
let message= eval("(" + e.data + ")");
},
websocketOnclose(e) {
console.log("connection closed (" + e + ")");
},
websocketSend(text) {
try {
this.websock.send(text);
console.log('发送的消息'+text);
} catch (err) {
console.log("send failed (" + err + ")");
}
},
}
三、手动关闭websocket
this.websock.close()
基本上的通信就实现啦,有什么疑问欢迎讨论 :)
|