一、websocket基础
二、websocket 封装
三、websocket 测试接通
一、websocket 基础
// WebSocket构造函数,创建WebSocket对象
let ws = new WebSocket('ws://localhost:8888')
// 连接成功后的回调函数
ws.onopen = function (params) {
console.log('客户端连接成功')
// 向服务器发送消息
ws.send('hello')
};
// 从服务器接受到信息时的回调函数
ws.onmessage = function (e) {
console.log('收到服务器响应', e.data)
};
// 连接关闭后的回调函数
ws.onclose = function(evt) {
console.log("关闭客户端连接");
};
// 连接失败后的回调函数
ws.onerror = function (evt) {
console.log("连接失败了");
};
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,这样服务端会抛异常。
window.onbeforeunload = function() {
ws.close();
}
二、websocket 封装
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)
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 测试接通
下载包:https://download.csdn.net/download/Web_Notes/88695650?spm=1001.2014.3001.5501
项目介绍:可以用来测试websocket接通后的效果,方便前端调整,就不用等后端接口了。
index.js为主要文件,运行命令为 node index.js
使用方法:
1.index.js 页面
2.index.html
3.浏览器打开index.html,打开控制台,如果能收到index.js发送的内容,就没问题了。
就把index.html里面websocket 请求的地址 复制到你其他需要使用的项目里,就可以接收websocket 进行调整处理了