创建websocket.js文件
import baseConfig from './config.js'
class websocket {
constructor(url) {
this.is_open_socket = false //避免重复连接
this.user_empower_close = false
this.url = `${baseConfig.webscoketUrl + url}` //地址
this.data = null
try {
return this.connectSocketInit('first')
} catch (e) {
this.is_open_socket = false
this.reconnect('next');
}
}
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit(type) {
this.socketTask = uni.connectSocket({
url: this.url,
success: () => {
console.log("正准备建立websocket中...");
// 返回实例
return this.socketTask
},
});
//监听是否连接成功
this.socketTask.onOpen((res) => {
console.log(type == 'first' ? "WebSocket连接正常!" : "WebSocket重连成功");
this.is_open_socket = true;
// 注:只有连接正常打开中 ,才能正常收到消息
this.onConnected()
})
// 这里仅是事件监听【如果socket关闭了会执行】关闭重新连接
this.socketTask.onClose((e) => {
this.is_open_socket = false;
if(!this.user_empower_close){
this.reconnect('next');
}
})
}
//发送消息
send(value) {
// 注:只有连接正常打开中 ,才能正常成功发送消息
this.socketTask.send({
data: value,
async success(res) {
console.log("消息发送成功", res);
},
async fail(e) {
console.log("消息发送失败", e);
}
});
}
//重新连接
reconnect(type="next") {
this.onReconnect()
//如果关闭的话,进行重连
if (!this.is_open_socket) {
this.connectSocketInit(type);
}
}
//外部获取消息
getMessage(callback) {
this.socketTask.onMessage((res) => {
return callback(res)
})
}
//关闭连接
close(e) {
this.is_open_socket = false
if(e.reason == "用户自己关闭"){
this.user_empower_close = true
this.socketTask.close({
async success(res) {
console.log("关闭成功", e);
},
async fail(e) {
console.log("关闭失败", e);
}
})
}else{
this.user_empower_close = false
}
}
/**
* 重新连接时触发
*/
onReconnect(){
console.log('WebSocket重新连接');
}
/**
* 连接成功时触发
*/
onConnected() {
console.log('WebSocket连接已打开');
}
/**
* 断开时触发
*/
onClosed() {
console.log('已断开连接')
}
//监听socket转态
onSocketStatus(callback){
return callback(this.is_open_socket?'Connecting':'Disconnected')
}
}
export default websocket;
引入的config文件是公共的数据,可以自行定义自己的websocket地址,这里就不说怎么弄了
具体使用就是
import wsRequest from "@/utils/websocket.js"
vue3用法:
const socket = ref(new wsRequest('你的socket地址'))
//onLoad
onLoad((option) => {
socket.value.onConnected = () => {
watchSocket()
}
})
//onUnload
onUnload(() => {
socket.value.close({
reason: '用户自己关闭'
})
})
//发送
const sendChat = async (data) => {
socket.value.send(JSON.stringify(data));
}
//接收
const watchSocket = () => {
socket.value.getMessage(opt => {
console.log("消息接收:", opt);
})
}
vue2用法:
data(){
socket: new wsRequest('你的socket地址')
}
onLoad(){
socket.onConnected = () => {
this.watchSocket()
}
}
onUnload(() => {
this.socket.close({
reason: '用户自己关闭'
})
})
method:{
sendChat(){
this.socket.send(JSON.stringify(data));
}
watchSocket(){
socket.value.getMessage(opt => { console.log("消息接收:", opt);}
})
}
}
结束!