uniapp中使用websocket

749 阅读1分钟

官方文档:uniapp.dcloud.net.cn/api/request…

export default {

    data(){
        return {
            // socket地址
            url:Config.websocketUrl,
            // 连接状态
            IsOpen:false,
            // SocketTask
            SocketTask:false,
            // 是否上线(会员id绑定客户端id,验证用户身份,通过则绑定)
            IsOnline:false, 
        }
    },
    
    methods:{
        // 连接
        Open(){
        
            if(this.IsOpen) return; // 防止重复连接
            // 连接
            this.SocketTask = uni.connectSocket({
                    url:this.url,
                    complete: (e)=> { },
            });
            if (!this.SocketTask) return;
            // 监听开启
            this.SocketTask.onOpen(()=>{
                    // 将连接状态设为已连接
                    console.log('连接成功!!!')
                    this.IsOpen = true;
                    // 用户绑定
                    this.UserBind();
            });
            // 监听信息
            this.Message();
            // 监听关闭
            this.SocketTask.onClose(()=>{
                    this.IsOpen = false;
                    this.SocketTask = false;
            });
            // 监听错误
            this.SocketTask.onError((e)=>{
                    this.IsOpen = false;
                    this.SocketTask = false;
            });
        },

        // 关闭连接
        Close(){
            if (this.IsOpen){
                this.SocketTask.close();
            }
        },

        // 监听信息
        Message(){
            this.SocketTask.onMessage((e)=>{
                console.log('监听服务器返回的信息', e)
                // 字符串转json
                let res = JSON.parse(e.data);
            })
        }
    
    }
    
}