Vue里怎么使用socket?(websocket)
第一步:封装socket.jsimport { Message } from 'iview';class Socket {constructor (wsurl, binaryType){this.wsurl = wsurlthis.websock = nullthis.binaryType = binaryTypethis.initWeb...
·
第一步:封装socket.js
import { Message } from 'iview';
class Socket {
constructor (wsurl, binaryType){
this.wsurl = wsurl
this.websock = null
this.binaryType = binaryType
this.initWebSocket()
}
initWebSocket(){
var that = this
this.websock = new WebSocket(this.wsurl)
if(this.binaryType){
this.websock.binaryType = this.binaryType
}
this.websock.onmessage = function(e){
that.webMessage(e)
}
this.websock.onclose = function(e){
that.webClose(e)
}
this.websock.onopen = function(){
that.webOpen()
}
this.websock.onerror = function(){
Message.error('websocket连接中断!请刷新重试')
}
}
sendSock(agentData, callback){
this.callback = callback
if(agentData){
if(this.websock.readyState === this.websock.OPEN){
this.webSend(agentData)
} else if(this.websock.readyState === this.websock.CONNECTING){
let that = this
setTimeout(function(){
that.webSend(agentData)
}, 300)
}else{
this.initWebSocket()
let that = this
setTimeout(function(){
that.webSend(agentData)
}, 500)
}
}
}
webMessage(e){
this.callback(e)
}
webSend(agentData){
this.websock.send(agentData)
}
webClose(e){
this.websock.close()
}
webOpen(){}
}
export default Socket
第二步:在vue文件里引入使用
socket的使用
//引入socket
import socket from "@/libs/socket.js"; //根据自己放的路径来引入socket
methods:{
//socket操作
initWebsocket(){
console.log("初始化websocket");
if(!this.websocket){
this.websocket = new socket(
//这里填写要请求socket的url字符串
)
this.websocket.sendSock("", this.websocketonmessage);
}
},
websocketonmessage(e){
console.log(e.data)
},
closeWebSocket(){
if(this.websocket != null){
this.websocket.webClose();
}
}
},
mounted(){
this.initWebsocket()
},
beforeDestroy(){
this.closeWebSocket()
}
更多推荐
已为社区贡献3条内容
所有评论(0)