一、websocket基础文章来源:https://www.toymoban.com/news/detail-553897.html
class MyWebScoket {
constructor(socketUrl) {
// super(socketUrl);
this.onopenFn = null
this.oncloseFn = null
this.onmessageFn = null
this.onerrorFn = null
this.socketUrl = socketUrl
this.socket = null
this.init()
}
init() {
let self = this
let timeStep = new Date().getTime();
self.socket = new WebSocket(self.socketUrl + timeStep);
self.socket.onopen = function (event) {
if (self.onopenFn) {
self.onopenFn(event)
}
}
self.socket.onmessageFn = function (event) {
console.log(event, '连接关闭')
if (self.onmessageFn) {
self.onmessageFn(event)
}
}
self.socket.onerrorFn = function (event) {
console.log(event, 'websocket通信发生错误')
if (self.onerrorFn) {
self.onerrorFn(event)
}
}
self.socket.oncloseFn = function (event) {
console.log(event, '处理业务')
if (self.oncloseFn) {
self.oncloseFn(event)
}
}
}
close() {
this.socket.close()
}
}
export default MyWebScoket
2.使用(vue)文章来源地址https://www.toymoban.com/news/detail-553897.html
import websocket from "./websocket.js"
setWebsocket(){
this.socket = new MyWebScoket(socketUrl)//socketUrl请求的地址
this.socket.onopenFn = this.onopen.bind(this)
this.socket.oncloseFn = this.onclose .bind(this)
this.socket.onmessageFn = this.onmessage .bind(this)
this.socket.onerrorFn = this.onerror.bind(this)
},
onopen(event){
//业务处理
},
onclose(event){
//业务处理
},
onmessage(event){
//业务处理
},
onerror(event){
//业务处理
},
到了这里,关于webSocket前端+webSocket封装的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!