uniapp项目 websocket封装

有偿封装一个websocket接口文件,可以成功接收发送信息。
接口成功后给150红包

提供参考实例:vue中封装webSocket,链接:https://blog.csdn.net/qq_39186346/article/details/81941664?spm=1001.2101.3001.6650.13&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EESLANDING%7Edefault-13-81941664-blog-83088349.pc_relevant_landingrelevant&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EESLANDING%7Edefault-13-81941664-blog-83088349.pc_relevant_landingrelevant&utm_relevant_index=14
【大致流程相通,区别更多还是路径、环境设置,执行过程中肯定还是需要调试,会存在报错】

您好,根据您提出的需要在uniapp项目 websocket封装的问题,为您解答如下:
1、 导入websocket相关依赖
2、后端建立socket服务
3、在前端项目中创建websocket.js文件进行封装,在该文件中加入socket的连接,断线重连,心跳等代码。

class WebsocketHelper{
    //初始化
    constructor() {
        //ws地址
        this.wsUrl = 'ws://' + '自己的地址';
        //websocket对象
        this.socketTask = null;
        this.state = false
        //是否人为关闭
        this.isPeopleClose = false;
        //断线重连机制
        this.reconnectInterval = null;
        //重连时间
        this.reconnectTimeOut = 10000;
        //重连次数
        this.reconnectCount = 5;

        // 断网重连
        uni.onNetworkStatusChange((res) => {
            if (res.isConnected) {
                this.connect();
            }
        });
 
    }
    //单例模式
    static getInstance() {
        if (!this.instance) {
            this.instance = new Chat();
        }
        return this.instance;
    }
    //建立连接
    connect() {
        try {
            let that = this
            this.socketTask = uni.connectSocket({
                url: this.wsUrl,
                success: () => {
                    console.log("正在连接");
                    return this.socketTask
                },
                fail: (err) => {
                    this.reconnect();
                },
            });
            //打开连接正常
            
            this.socketTask.onOpen(async (res) => {
                console.log(this.wsUrl)
                console.log("打开成功");
                //清除断开重连定时器,
                clearInterval(this.reconnectInterval);
                this.state = false
                //设置重连次数
                this.reconnectCount = 10;
                //重置人为关闭状态
                this.isPeopleClose = false;
 
                //监听接收消息
                this.socketTask.onMessage((res) => {
                      console.log('收到数据')
                       // 可以针对自己的实际业务对返回的数据进行处理
                });
            })
            // 检测到发生异常时的回调方法
            this.socketTask.onError((err) => {
                console.error('onError',this.state);
                if(this.state == false){
                    //重连
                    this.reconnect();
                }
                
            })
 
            this.socketTask.onClose(() => {
                console.log('onClose');
                //重连
                this.reconnect();
            })
 
        } catch (e) {
            //重连
            this.reconnect();
        }
    }
 
    //手动关闭连接
    close() {
        console.log('close');
        this.isPeopleClose = true;
        this.socketTask.close({
            success(res) {
                console.log("关闭了")
            },
            fail(err) {
 
            }
        })
    }
 
    //断线重连
    reconnect() {
        //非人为关闭则尝试重连
        console.log('进行重连');
        if (!this.isPeopleClose) {
            this.state = true
            this.reconnectInterval = setInterval(() => {
                //如果重连次数小于0则清除定时器
                if (this.reconnectCount > 0) {
                    console.log('重连,第' + this.reconnectCount + '次');
                    this.connect();
                    this.reconnectCount--;
                } else {
                    clearInterval(this.reconnectInterval);
                    let that = this
                    uni.showModal({
                        title: '提示',
                        cancelText: '再次连接',
                        confirmText: '确定',
                        showCancel:true,    
                        content: '连接已断开,请检查网络!',
                        success: function(res) {
                            if (res.cancel) {
                                that.reconnectCount = 10;
                                that.reconnect();
                            } else if (res.confirm) {
                                console.log('已取消');
                            }
                        }
                    });
                }
            }, this.reconnectTimeOut);
        }
    }
}
 
export default WebsocketHelper;


当然还有挺多资料的,都有源代码,可执行。为您推荐一些:
uniapp websocekt的封装:https://www.jianshu.com/p/bcce5c983155
uniapp小程序webSocket封装、断线重连、心跳检测:http://events.jianshu.io/p/cf39e27c6e3d
UniAPP(仅H5端)封装全局websocket:https://blog.csdn.net/daeiqiu/article/details/128672357

4、调用封装好的代码:
1)import引入写好的js
2)调用初始化方法
3)发送消息并在回调函数中接受返回的消息

send(JSON.stringify({msg:'发送的信息'}))
//监听或接收的数据
  uni.onMessage((res)=>{

    console.log(JSON.parse(res.data))               
  })

5、不需要使用时,关闭连接:

removeWebsocket()

该回答引用ChatGPT

测试有问题可以回复我

可以封装一个websocket接口文件,以便在需要的地方调用它来发送和接收消息。下面是一个简单的websocket接口文件示例:

var socketTask = null;
var isConnected = false;

// 连接WebSocket服务器
function connectWebSocket(url, onOpen, onMessage, onClose, onError) {
  socketTask = uni.connectSocket({
    url: url,
    complete: function(res) {
      console.log('WebSocket连接完成');
    }
  });
  
  // 监听WebSocket连接打开事件
  socketTask.onOpen(function(res) {
    console.log('WebSocket连接已打开');
    isConnected = true;
    if (typeof onOpen == 'function') {
      onOpen(res);
    }
  });
  
  // 监听WebSocket接收到服务器的消息事件
  socketTask.onMessage(function(res) {
    console.log('WebSocket接收到消息:', res);
    if (typeof onMessage == 'function') {
      onMessage(res);
    }
  });
  
  // 监听WebSocket连接关闭事件
  socketTask.onClose(function(res) {
    console.log('WebSocket连接已关闭');
    isConnected = false;
    if (typeof onClose == 'function') {
      onClose(res);
    }
  });
  
  // 监听WebSocket错误事件
  socketTask.onError(function(res) {
    console.log('WebSocket连接发生错误');
    if (typeof onError == 'function') {
      onError(res);
    }
  });
}

// 断开WebSocket连接
function closeWebSocket() {
  if (socketTask != null) {
    socketTask.close({
      complete: function(res) {
        console.log('WebSocket连接已断开');
        isConnected = false;
      }
    });
  }
}

// 发送消息到WebSocket服务器
function sendWebSocketMessage(data) {
  if (socketTask != null && isConnected) {
    socketTask.send({
      data: data,
      complete: function(res) {
        console.log('WebSocket发送消息成功:', res);
      }
    });
  }
}

export default {
  connect: connectWebSocket,
  close: closeWebSocket,
  send: sendWebSocketMessage
}

在这个websocket接口文件中,我们首先定义了一个变量socketTask,用于存储WebSocket连接对象。然后,我们定义了几个函数来连接、断开和发送消息到WebSocket服务器。具体来说,我们使用uni.connectSocket()函数来连接WebSocket服务器,然后使用socketTask.onOpen()、socketTask.onMessage()、socketTask.onClose()和socketTask.onError()函数来监听WebSocket的打开、接收消息、关闭和错误事件。在发送消息时,我们使用socketTask.send()函数来将消息发送到WebSocket服务器。最后,我们使用export default来导出这些函数,以便在需要的地方调用它们。

你可以将这个文件保存为一个js文件,并在需要的地方通过import来引入它。例如,你可以在vue页面中使用以下方式来调用它:

<template>
  <div>
    <button @click="connectWebSocket">连接WebSocket</button>
    <button @click="closeWebSocket">关闭WebSocket</button>
    <button @click="sendWebSocketMessage">发送消息</button>
  </div>
</template>

<script>
import WebSocket from '@/common/websocket.js'

export default {
  data() {
    return {
      websocketUrl: 'ws://localhost:8080',
      message: ''
    }
  },
  methods: {
    // 连接WebSocket服务器
    connectWebSocket() {
      WebSocket.connect(this.websocketUrl, function(res) {
        console.log('WebSocket连接已打开');
      }, function(res) {
        console.log('WebSocket接收到消息:', res);
        this.message = res.data;
      }, function(res) {
        console.log('WebSocket连接已关闭');
      }, function(res) {
        console.log('WebSocket连接发生错误');
      });
    },
    
    // 关闭WebSocket连接
    closeWebSocket() {
      WebSocket.close();
    },
    
    // 发送消息到WebSocket服务器
    sendWebSocketMessage() {
      WebSocket.send(this.message);
    }
  }
}
</script>


以下答案基于ChatGPT与GISer Liu编写:
以下是一个简单的uniapp项目中使用websocket的示例:

①首先,在uniapp项目的根目录下新建一个文件夹 utils,并在该文件夹下创建一个名为 websocket.js 的文件。

在 websocket.js 文件中封装websocket接口,示例代码如下:

let socket = null;

// 初始化websocket连接
function initWebSocket() {
  socket = new WebSocket('ws://localhost:8080');

  socket.onopen = function () {
    console.log('WebSocket连接已打开');
  };

  socket.onmessage = function (event) {
    console.log('收到消息:', event.data);
  };

  socket.onclose = function (event) {
    console.log('WebSocket连接已关闭');
  };

  socket.onerror = function (event) {
    console.log('WebSocket连接发生错误');
  };
}

// 发送消息
function sendWebSocketMsg(msg) {
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(msg);
  } else {
    console.log('WebSocket连接没有准备好');
  }
}

export default {
  initWebSocket,
  sendWebSocketMsg
}

②在需要使用websocket的页面中引入 websocket.js 文件,并调用其中的方法。示例代码如下:

import WebSocketApi from '@/utils/websocket.js';

export default {
  mounted() {
    WebSocketApi.initWebSocket();
  },
  methods: {
    sendMsg() {
      WebSocketApi.sendWebSocketMsg('hello world');
    }
  }
}

在页面的 mounted 钩子函数中调用 initWebSocket 方法初始化websocket连接,然后在需要发送消息的方法中调用 sendWebSocketMsg 方法发送消息。

注意,以上示例代码仅供参考,具体实现需要根据项目实际情况进行修改。同时,需要根据实际情况处理接收到的消息。

参考GPT和自己的思路,如果你能提供代码更好。我提供一个简单的 JavaScript WebSocket 封装示例:

class MyWebSocket {
  constructor(url) {
    this.url = url;
    this.socket = null;
  }

  connect() {
    this.socket = new WebSocket(this.url);
    this.socket.onopen = this.onOpen.bind(this);
    this.socket.onclose = this.onClose.bind(this);
    this.socket.onerror = this.onError.bind(this);
    this.socket.onmessage = this.onMessage.bind(this);
  }

  onOpen(event) {
    console.log("Connected to WebSocket server");
  }

  onClose(event) {
    console.log("Disconnected from WebSocket server");
  }

  onError(event) {
    console.error("WebSocket error observed:", event);
  }

  onMessage(event) {
    console.log(`Message received: ${event.data}`);
  }

  send(data) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(data));
      console.log(`Message sent: ${JSON.stringify(data)}`);
    } else {
      console.error("WebSocket is not connected");
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

// 创建一个 WebSocket 实例
const myWebSocket = new MyWebSocket("ws://localhost:8080");

// 连接 WebSocket
myWebSocket.connect();

// 发送消息
myWebSocket.send({ message: "Hello, WebSocket!" });

// 关闭 WebSocket 连接
myWebSocket.close();

这里定义了一个 MyWebSocket 类,封装了 WebSocket 的连接、关闭、错误处理、消息接收和发送功能。使用时,可以创建一个 WebSocket 实例,连接 WebSocket 服务器并发送、接收消息。

如果对您有帮助,请给与采纳,谢谢。



class Ws{
    //初始化
    constructor() {
        //ws地址
        this.wsUrl = 'ws://' + '自己的地址';
 
        //websocket对象
        this.socketTask = null;
        this.state = false
        //是否人为关闭
        this.isPeopleClose = false;
        //断线重连机制
        this.reconnectInterval = null;
        //重连时间
        this.reconnectTimeOut = 5000;
        //重连次数
        this.reconnectCount = 10;
 
        // 断网重连
        uni.onNetworkStatusChange((res) => {
            if (res.isConnected) {
                this.connect();
            }
        });
 
    }
    //单例模式可参考链接 https://www.runoob.com/design-pattern/singleton-pattern.html
    static getInstance() {
        if (!this.instance) {
            this.instance = new Chat();
        }
        return this.instance;
    }
    //建立连接
    connect() {
        try {
            let that = this
            this.socketTask = uni.connectSocket({
                url: this.wsUrl,
                success: () => {
                    console.log("正在建立连接");
                    return this.socketTask
                },
                fail: (err) => {
                    this.reconnect();
                },
            });
            //打开连接正常
            
            this.socketTask.onOpen(async (res) => {
                console.log(this.wsUrl)
                console.log("打开连接成功");
                //清除断开重连定时器,
                clearInterval(this.reconnectInterval);
                this.state = false
                //设置重连次数
                this.reconnectCount = 10;
                //重置人为关闭状态
                this.isPeopleClose = false;
 
                //监听接收消息
                this.socketTask.onMessage((res) => {
                      console.log('接收到数据')
                       // 可以针对自己的实际业务对返回的数据进行处理
                });
            })
            // 检测到发生异常时的回调方法
            this.socketTask.onError((err) => {
                console.error('onError',this.state);
                if(this.state == false){
                    //重连
                    this.reconnect();
                }
                
            })
 
            this.socketTask.onClose(() => {
                console.log('onClose');
                //重连
                this.reconnect();
            })
 
        } catch (e) {
            //重连
            this.reconnect();
        }
    }
 
    //手动关闭连接
    close() {
        console.log('close');
        this.isPeopleClose = true;
        this.socketTask.close({
            success(res) {
                console.log("关闭成功")
            },
            fail(err) {
 
            }
        })
    }
 
    //断线重连
    reconnect() {
        //非人为关闭则尝试重连
        console.log('进行断线重连');
        if (!this.isPeopleClose) {
            this.state = true
            this.reconnectInterval = setInterval(() => {
                //如果重连次数小于0则清除定时器
                if (this.reconnectCount > 0) {
                    console.log('正在重连,第' + this.reconnectCount + '次');
                    this.connect();
                    this.reconnectCount--;
                } else {
                    clearInterval(this.reconnectInterval);
                    let that = this
                    uni.showModal({
                        title: '提示',
                        cancelText: '继续连接',
                        confirmText: '确定',
                        showCancel:true,    
                        content: '断开连接,请检查网络!',
                        success: function(res) {
                            if (res.cancel) {
                                that.reconnectCount = 10;
                                that.reconnect();
                            } else if (res.confirm) {
                                console.log('用户点击取消');
                            }
                        }
                    });
                }
            }, this.reconnectTimeOut);
        }
    }
}
 
export default Ws;
 import Ws from "../../untils/websocket.js"; //在需要使用的页面中引用上述js文件

         Ws .getInstance().connect()    // 连接websocket

以下是一个简单的WebSocket封装实现,使用JavaScript,适用于uniapp项目:

// websocket.js

class WebSocketApi {
  constructor(url) {
    this.url = url;
    this.reconnectCount = 0;
    this.instance = null;
    this.timer = null;
    this.init();
  }

  init() {
    this.instance = uni.connectSocket({
      url: this.url
    });

    this.instance.onOpen(() => {
      console.log('WebSocket 连接已打开');
      this.reconnectCount = 0;
    });

    this.instance.onMessage((res) => {
      console.log('WebSocket 接收消息:', res.data);
    });

    this.instance.onClose((res) => {
      console.log('WebSocket 连接已关闭:', res);
      if (this.reconnectCount < 3) {
        console.log('WebSocket 将尝试重新连接');
        this.reconnectCount++;
        this.reconnect();
      } else {
        console.log('WebSocket 连接已超过重连次数限制');
      }
    });

    this.instance.onError((res) => {
      console.log('WebSocket 连接错误:', res);
      this.reconnect();
    });
  }

  send(data) {
    if (this.instance && this.instance.readyState === 1) {
      this.instance.send({
        data: JSON.stringify(data)
      });
      console.log('WebSocket 发送消息:', data);
    } else {
      console.log('WebSocket 尚未连接');
    }
  }

  close() {
    this.instance && this.instance.close();
  }

  reconnect() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      console.log('WebSocket 正在重新连接');
      this.init();
    }, 5000);
  }
}

export default WebSocketApi;

使用示例:


// 使用示例

import WebSocketApi from './websocket.js';

const webSocket = new WebSocketApi('ws://localhost:3000');

webSocket.send({ type: 'message', content: 'Hello' });

webSocket.close();
//websocket.js
var webSocket = null;
var isConnect = false; //连接状态
var globalCallback = function(e){ console.log(e) };//定义外部接收数据的回调函数
var reConnectNum = 0;//重连次数

var websocketUrl =  `ws://api:端口号/websocket/${uni.getStorageSync("userinfo").uid}`;

//心跳设置
var heartCheck = {
    heartbeatData:{
        DevID:{
            value:uni.getStorageSync("userinfo").uid
        },
        DevHeart:{
            value:uni.getStorageSync("userinfo").uid
        }   
    },//心跳包
    timeout: 60 * 1000, //每段时间发送一次心跳包 这里设置为60s
    heartbeat: null, //延时发送消息对象(启动心跳新建这个对象,收到消息后重置对象)
    start: function () {
        this.heartbeat = setInterval(()=>{
            if (isConnect){
                webSocketSend("心跳机制");
            }else{
                this.clear();
            }
        }, this.timeout);
    },
    reset: function () {
        clearInterval(this.heartbeat);
        this.start();
    },
    clear:function(){
        clearInterval(this.heartbeat);
    }
}

//初始化websocket
function initWebSocket(callback) {
    //此callback为在其他地方调用时定义的接收socket数据的函数
    if(callback){
        if(typeof callback == 'function'){
            globalCallback = callback     
        }else{
            throw new Error("callback is not a function")
        }
    }
    if ("WebSocket" in window) {
        webSocket = new WebSocket(websocketUrl);//创建socket对象
    } else {
        Message({
            message: '该浏览器不支持websocket!',
            type: 'warning'
        });
        return
    }
    //打开
    webSocket.onopen = function() {
        webSocketOpen();
    };
    //收信
    webSocket.onmessage = function(e) {
        webSocketOnMessage(e);
    };
    //关闭
    webSocket.onclose = function(e) {
        webSocketOnClose(e);
    };
    //连接发生错误的回调方法
    webSocket.onerror = function(e) {
        webSocketonError(e);
    };
}

//连接socket建立时触发
function webSocketOpen() {
    console.log("WebSocket连接成功");
    //首次握手
    webSocketSend("心跳机制");
    isConnect = true;
    heartCheck.start();
    reConnectNum = 0;
}

//客户端接收服务端数据时触发,e为接受的数据对象
function webSocketOnMessage(e) {
    console.log("websocket信息:");
    console.log(e.data)
    let arr = []
    try{
        var data = JSON.parse(e.data)
        if(typeof data == 'object' && data){
            arr.push(data)
            console.log("处理后得数据",arr)
            globalCallback(arr);//将data传给在外定义的接收数据的函数,至关重要。
        }else{
            return false;
        }
    }catch(e){
        return false;
    }
    
}

//socket关闭时触发
function webSocketOnClose(e){
    heartCheck.clear();
    isConnect = false; //断开后修改标识
    console.log(e)
    console.log('webSocket已经关闭 (code:' + e.code + ')')
    //被动断开,重新连接
    if(e.code == 1006){
        if(reConnectNum < 3){
            initWebSocket();
            ++reConnectNum;
        }else{
            v.$message({
                message: 'websocket连接不上,请刷新页面或联系开发人员!',
                type: 'warning'
            });
        }
    }
}

//连接发生错误的回调方法
function webSocketonError(e){
    heartCheck.clear();
    isConnect = false; //断开后修改标识
    console.log("WebSocket连接发生错误:");
    console.log(e);
}


//发送数据
function webSocketSend(data) {
    webSocket.send(JSON.stringify(data));//在这里根据自己的需要转换数据格式
}
//在其他需要socket地方主动关闭socket
function closeWebSocket(e) {
    webSocket.close();
    heartCheck.clear();
    isConnect = false;
    reConnectNum = 0;
}
//在其他需要socket地方接受数据
function getSock(callback) {
    globalCallback = callback
}
//在其他需要socket地方调用的函数,用来发送数据及接受数据
function sendSock(agentData) {
    //下面的判断主要是考虑到socket连接可能中断或者其他的因素,可以重新发送此条消息。
    switch (webSocket.readyState) {
        //CONNECTING:值为0,表示正在连接。
        case webSocket.CONNECTING:
            setTimeout(function() {
                sendSock(agentData, callback);
            }, 1000);
        break;
        //OPEN:值为1,表示连接成功,可以通信了。
        case webSocket.OPEN:
            webSocketSend(agentData);
        break;
        //CLOSING:值为2,表示连接正在关闭。
        case webSocket.CLOSING:
            setTimeout(function() {
                sendSock(agentData, callback);
            }, 1000);
        break;
        //CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
        case webSocket.CLOSED:
        // do something
        break;
        default:
        // this never happens
        break;
    }
}

export default {
  initWebSocket,
  closeWebSocket,
  sendSock,
  getSock
};
在main.js中引入注册
import WS from "@/common/js/websocket.js"
Vue.prototype.$ws = WS;

在页面中使用
onLoad(option) {
            let self = this;
            self.$ws.initWebSocket(self.getsocketResult);//getsocketResult socket信息返回接受函数
        },
beforeDestroy() {
            this.$ws.closeWebSocket();
        },

加油。。小程序应该不支持ip,只支持 wss (https)

this.socketTask = uni.connectSocket({
                url: 'wss://192.168.3.70/websocket', //仅为示例,并非真实接口地址。
                success: (resData) => {
                    console.log("链接成功")
                    console.log(resData)
                },
                fail: (err) => {
                    console.log("错误信息")
                    console.log(err)
                },
                complete: (res)=> {
                    console.log("都要执行")
                }
            });
            uni.onSocketMessage(function (res) {
                console.log(res)
              console.log('收到服务器内容:' + res.data);
            });
            
            console.log(this.socketTask)
 
 

以下是一个简单的uniapp项目websocket封装的示例代码:

// websocket.js
export default {
  socketTask: null,
  // 连接websocket
  connect(url, onOpen, onMessage, onError, onClose) {
    this.socketTask = uni.connectSocket({
      url: url,
      success: function() {
        console.log('websocket连接成功');
      }
    });
    this.socketTask.onOpen(onOpen);
    this.socketTask.onMessage(onMessage);
    this.socketTask.onError(onError);
    this.socketTask.onClose(onClose);
  },
  // 发送消息
  send(message) {
    this.socketTask.send({
      data: message
    });
  },
  // 关闭websocket
  close() {
    this.socketTask.close();
  }
}


使用时,只需要引入websocket.js文件,然后调用其中的connect、send、close方法即可。例如:

// index.vue
import websocket from '@/utils/websocket.js'

export default {
  data() {
    return {
      message: ''
    }
  },
  mounted() {
    websocket.connect('ws://localhost:8080/ws', this.onOpen, this.onMessage, this.onError, this.onClose)
  },
  methods: {
    onOpen() {
      console.log('websocket连接已打开')
    },
    onMessage(res) {
      console.log('收到消息:', res.data)
      this.message = res.data
    },
    onError(err) {
      console.log('websocket出错:', err)
    },
    onClose() {
      console.log('websocket已关闭')
    },
    sendMessage() {
      websocket.send(this.message)
    },
    closeSocket() {
      websocket.close()
    }
  }
}


在上面的示例中,我们在mounted生命周期中调用了websocket.connect方法,传入了websocket的连接地址以及四个回调函数,分别处理连接成功、接收消息、出错和关闭连接时的操作。接收到的消息通过将其赋值给data中的message属性来更新页面中的内容。同时,我们定义了sendMessage和closeSocket两个方法,用于发送消息和关闭连接

步骤

1、参考官方文档,引入websocket组件
2、定义空数组用来储存接受的消息
3、进行初始化连接
4、定义websocket组件的监听事件及处理函数

代码

import websocket from "../components/websocket/websocket.js"

Page({
    data: {
        messageList: [],   // 消息列表
    },
    onLoad: function () {
        this.websocket = websocket();    // 初始化websocket
        // 添加消息监听
        this.websocket.onMessage(this.onMessge)
    },
    // 消息回调
    onMessge({data}) {
        let messageList = this.data.messageList,
            message = JSON.parse(data);
        messageList.push(message);
        this.setMessageList(messageList);
    },
    // 发送消息
    sendMessage() {
        let data = ' 后台发送消息 ';
        this.websocket.send(data);
    },
    // 设置消息列表
    setMessageList(messageList) {
        this.setData({
            messageList
        })
    },
    // 关闭连接
    closeSocket() {
        this.websocket.close({
            success: () => {
                console.log('断开连接')
            }
        })
    }
})

1.文件夹common下新建webSocket.js

class webSocketClass {

  constructor(url, time) {

    this.url = url

    this.data = null

    this.isCreate = false // WebSocket 是否创建成功

    this.isConnect = false // 是否已经连接

    this.isInitiative = false // 是否主动断开

    this.timeoutNumber = time // 心跳检测间隔

    this.heartbeatTimer = null // 心跳检测定时器

    this.reconnectTimer = null // 断线重连定时器

    this.socketExamples = null // websocket实例

    this.againTime = 3 // 重连等待时间(单位秒)

  }

  // 初始化websocket连接

  initSocket() {

    const _this = this

    this.socketExamples = uni.connectSocket({

      url: _this.url,

      header: {

        'content-type': 'application/json'

      },

      success: (res) => {

        _this.isCreate = true

        console.log(res)

      },

      fail: (rej) => {

        console.error(rej)

        _this.isCreate = false

      }

    })

    this.createSocket()

  }

  // 创建websocket连接

  createSocket() {

    if (this.isCreate) {

      console.log('WebSocket 开始初始化')

      // 监听 WebSocket 连接打开事件

      try {

        this.socketExamples.onOpen(() => {

          console.log('WebSocket 连接成功')

          this.isConnect = true

          clearInterval(this.heartbeatTimer)

          clearTimeout(this.reconnectTimer)

          // 打开心跳检测

          this.heartbeatCheck()

        })

        // 监听 WebSocket 接受到服务器的消息事件

        this.socketExamples.onMessage((res) => {

          console.log('收到消息')

          uni.$emit('message', res)

        })

        // 监听 WebSocket 连接关闭事件

        this.socketExamples.onClose(() => {

          console.log('WebSocket 关闭了')

          this.isConnect = false

          this.reconnect()

        })

        // 监听 WebSocket 错误事件

        this.socketExamples.onError((res) => {

          console.log('WebSocket 出错了')

          console.log(res)

          this.isInitiative = false

        })

      } catch (error) {

        console.warn(error)

      }

    } else {

      console.warn('WebSocket 初始化失败!')

    }

  }

  // 发送消息

  sendMsg(value) {

    const param = JSON.stringify(value)

    return new Promise((resolve, reject) => {

      this.socketExamples.send({

        data: param,

        success() {

          console.log('消息发送成功')

          resolve(true)

        },

        fail(error) {

          console.log('消息发送失败')

          reject(error)

        }

      })

    })

  }

  // 开启心跳检测

  heartbeatCheck() {

    console.log('开启心跳')

    this.data = { state: 1, method: 'heartbeat' }

    this.heartbeatTimer = setInterval(() => {

      this.sendMsg(this.data)

    }, this.timeoutNumber * 1000)

  }

  // 重新连接

  reconnect() {

    // 停止发送心跳

    clearTimeout(this.reconnectTimer)

    clearInterval(this.heartbeatTimer)

    // 如果不是人为关闭的话,进行重连

    if (!this.isInitiative) {

      this.reconnectTimer = setTimeout(() => {

        this.initSocket()

      }, this.againTime * 1000)

    }

  }

  // 关闭 WebSocket 连接

  closeSocket(reason = '关闭') {

    const _this = this

    this.socketExamples.close({

      reason,

      success() {

        _this.data = null

        _this.isCreate = false

        _this.isConnect = false

        _this.isInitiative = true

        _this.socketExamples = null

        clearInterval(_this.heartbeatTimer)

        clearTimeout(_this.reconnectTimer)

        console.log('关闭 WebSocket 成功')

      },

      fail() {

        console.log('关闭 WebSocket 失败')

      }

    })

  }

}

export default webSocketClass

2.在App.vue的globalData添加===》socketObj:null

3.引用 import WebSocketClass from '../../common/webSocket'

4.使用

  onLoad(){uni.$on('message', this.getMessage)},

onUnload() {

  uni.$off('message', this.getMessage)

},

methods:{getMessage(msg) {}

console.log(msg)

},

在需要使用的地方使用 

if (getApp().globalData.socketObj) {

// 如果sockt实例未连接

if (!getApp().globalData.socketObj.isConnect) {

  getApp().globalData.socketObj.initSocket()

}

  } else {

// 如果没有sockt实例,则创建

getApp().globalData.socketObj = new WebSocketClass(

  `wss:这里是地址`,

  60

)

getApp().globalData.socketObj.initSocket()

  }