liziyu 发布的文章

转载一(uniapp专用):

function Push(options) {
    this.doNotConnect = 0;
    options = options || {};
    options.heartbeat  = options.heartbeat || 25000;
    options.pingTimeout = options.pingTimeout || 10000;
    this.config = options;
    this.uid = 0;
    this.channels = {};
    this.connection = null;
    this.pingTimeoutTimer = 0;
    Push.instances.push(this);
    this.createConnection();
}

Push.prototype.checkoutPing = function() {
    var _this = this;
    setTimeout(function () {
        if (_this.connection.state === 'connected') {
            _this.connection.send('{"event":"pusher:ping","data":{}}');
            if (_this.pingTimeoutTimer) {
                clearTimeout(_this.pingTimeoutTimer);
                _this.pingTimeoutTimer = 0;
            }
            _this.pingTimeoutTimer = setTimeout(function () {
                _this.connection.closeAndClean();
                if (!_this.connection.doNotConnect) {
                    _this.connection.waitReconnect();
                }
            }, _this.config.pingTimeout);
        }
    }, this.config.heartbeat);
};

Push.prototype.channel = function (name) {
    return this.channels.find(name);
};
Push.prototype.allChannels = function () {
    return this.channels.all();
};
Push.prototype.createConnection = function () {
    if (this.connection) {
        throw Error('Connection already exist');
    }
    var _this = this;
    var url = this.config.url;
    function updateSubscribed () {
        for (var i in _this.channels) {
            _this.channels[i].subscribed = false;
        }
    }
    this.connection = new Connection({
        url: url,
        app_key: this.config.app_key,
        onOpen: function () {
            _this.connection.state  = 'connecting';
            _this.checkoutPing();
        },
        onMessage: function(params) {
            if(_this.pingTimeoutTimer) {
                clearTimeout(_this.pingTimeoutTimer);
                _this.pingTimeoutTimer = 0;
            }

            params = JSON.parse(params.data);
            var event = params.event;
            var channel_name = params.channel;

            if (event === 'pusher:pong') {
                _this.checkoutPing();
                return;
            }
            if (event === 'pusher:error') {
                throw Error(params.data.message);
            }
            var data = JSON.parse(params.data), channel;
            if (event === 'pusher_internal:subscription_succeeded') {
                channel = _this.channels[channel_name];
                channel.subscribed = true;
                channel.processQueue();
                channel.emit('pusher:subscription_succeeded');
                return;
            }
            if (event === 'pusher:connection_established') {
                _this.connection.socket_id = data.socket_id;
                _this.connection.state = 'connected';
                _this.subscribeAll();
            }
            if (event.indexOf('pusher_internal') !== -1) {
                console.log("Event '"+event+"' not implement");
                return;
            }
            channel = _this.channels[channel_name];
            if (channel) {
                channel.emit(event, data);
            }
        },
        onClose: function () {
            updateSubscribed();
        },
        onError: function () {
            updateSubscribed();
        }
    });
};
Push.prototype.disconnect = function () {
    this.connection.doNotConnect = 1;
    this.connection.close();
};

Push.prototype.subscribeAll = function () {
    if (this.connection.state !== 'connected') {
        return;
    }
    for (var channel_name in this.channels) {
        //this.connection.send(JSON.stringify({event:"pusher:subscribe", data:{channel:channel_name}}));
        this.channels[channel_name].processSubscribe();
    }
};

Push.prototype.unsubscribe = function (channel_name) {
    if (this.channels[channel_name]) {
        delete this.channels[channel_name];
        if (this.connection.state === 'connected') {
            this.connection.send(JSON.stringify({event:"pusher:unsubscribe", data:{channel:channel_name}}));
        }
    }
};
Push.prototype.unsubscribeAll = function () {
    var channels = Object.keys(this.channels);
    if (channels.length) {
        if (this.connection.state === 'connected') {
            for (var channel_name in this.channels) {
                this.unsubscribe(channel_name);
            }
        }
    }
    this.channels = {};
};
Push.prototype.subscribe = function (channel_name) {
    if (this.channels[channel_name]) {
        return this.channels[channel_name];
    }
    if (channel_name.indexOf('private-') === 0) {
        return createPrivateChannel(channel_name, this);
    }
    if (channel_name.indexOf('presence-') === 0) {
        return createPresenceChannel(channel_name, this);
    }
    return createChannel(channel_name, this);
};
Push.instances = [];

function createChannel(channel_name, push)
{
    var channel = new Channel(push.connection, channel_name);
    push.channels[channel_name] = channel;
    channel.subscribeCb = function () {
        push.connection.send(JSON.stringify({event:"pusher:subscribe", data:{channel:channel_name}}));
    }
    return channel;
}

function createPrivateChannel(channel_name, push)
{
    var channel = new Channel(push.connection, channel_name);
    push.channels[channel_name] = channel;
    channel.subscribeCb = function () {
        __ajax({
            url: push.config.auth,
            type: 'POST',
            data: {channel_name: channel_name, socket_id: push.connection.socket_id},
            success: function (data) {
                data = JSON.parse(data);
                data.channel = channel_name;
                push.connection.send(JSON.stringify({event:"pusher:subscribe", data:data}));
            },
            error: function (e) {
                throw Error(e);
            }
        });
    };
    channel.processSubscribe();
    return channel;
}

function createPresenceChannel(channel_name, push)
{
    return createPrivateChannel(channel_name, push);
}

/*window.addEventListener('online',  function(){
    var con;
    for (var i in Push.instances) {
        con = Push.instances[i].connection;
        con.reconnectInterval = 1;
        if (con.state === 'connecting') {
            con.connect();
        }
    }
});*/

function Connection(options) {
    this.dispatcher = new Dispatcher();
    __extends(this, this.dispatcher);
    var properies = ['on', 'off', 'emit'];
    for (var i in properies) {
        this[properies[i]] = this.dispatcher[properies[i]];
    }
    this.options = options;
    this.state = 'initialized'; //initialized connecting connected disconnected
    this.doNotConnect = 0;
    this.reconnectInterval = 1;
    this.connection = null;
    this.reconnectTimer = 0;
    this.connect();
}

Connection.prototype.updateNetworkState = function(state){
    var old_state = this.state;
    this.state = state;
    if (old_state !== state) {
        this.emit('state_change', { previous: old_state, current: state });
    }
};

Connection.prototype.connect = function () {
    this.doNotConnect = 0;
    if (this.networkState == 'connecting' || this.networkState == 'established') {
        console.log('networkState is ' + this.networkState + ' and do not need connect');
        return;
    }
    if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = 0;
    }

    this.closeAndClean();

    var options = this.options;
    var _this = this;
    _this.updateNetworkState('connecting');
    var cb = function(){
        uni.onSocketOpen(function (res) {
            _this.reconnectInterval = 1;
            if (_this.doNotConnect) {
                _this.updateNetworkState('closing');
                uni.closeSocket();
                return;
            }
            _this.updateNetworkState('established');
            if (options.onOpen) {
                options.onOpen(res);
            }
        });

        if (options.onMessage) {
            uni.onSocketMessage(options.onMessage);
        }

        uni.onSocketClose(function (res) {
            _this.updateNetworkState('disconnected');
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onClose) {
                options.onClose(res);
            }
        });

        uni.onSocketError(function (res) {
            _this.close();
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onError) {
                options.onError(res);
            }
        });
    };
    uni.connectSocket({
        url: options.url,
        fail: function (res) {
            console.log('uni.connectSocket fail');
            console.log(res);
            _this.updateNetworkState('disconnected');
            _this.waitReconnect();
        },
        success: function() {

        }
    });
    cb();
}

Connection.prototype.connect = function () {
    this.doNotConnect = 0;
    if (this.state === 'connected') {
        console.log('networkState is "' + this.state + '" and do not need connect');
        return;
    }
    if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = 0;
    }

    this.closeAndClean();

    var options = this.options;

    this.updateNetworkState('connecting');

    var _this = this;
    var cb = function(){
        uni.onSocketOpen(function (res) {
            _this.reconnectInterval = 1;
            if (_this.doNotConnect) {
                _this.updateNetworkState('disconnected');
                uni.closeSocket();
                return;
            }
            if (options.onOpen) {
                options.onOpen(res);
            }
        });

        if (options.onMessage) {
            uni.onSocketMessage(options.onMessage);
        }

        uni.onSocketClose(function (res) {
            _this.updateNetworkState('disconnected');
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onClose) {
                options.onClose(res);
            }
        });

        uni.onSocketError(function (res) {
            _this.close();
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onError) {
                options.onError(res);
            }
        });
    };
    uni.connectSocket({
        url: options.url+'/app/'+options.app_key,
        fail: function (res) {
            console.log('uni.connectSocket fail');
            console.log(res);
            _this.updateNetworkState('disconnected');
            _this.waitReconnect();
        },
        success: function() {

        }
    });
    cb();
}

Connection.prototype.closeAndClean = function () {
    if (this.state === 'connected') {
        uni.closeSocket();
    }
    this.updateNetworkState('disconnected');
};

Connection.prototype.waitReconnect = function () {
    if (this.state === 'connected' || this.state === 'connecting') {
        return;
    }
    if (!this.doNotConnect) {
        this.updateNetworkState('connecting');
        var _this = this;
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
        }
        this.reconnectTimer = setTimeout(function(){
            _this.connect();
        }, this.reconnectInterval);
        if (this.reconnectInterval < 1000) {
            this.reconnectInterval = 1000;
        } else {
            // 每次重连间隔增大一倍
            this.reconnectInterval = this.reconnectInterval * 2;
        }
        // 有网络的状态下,重连间隔最大2秒
        if (this.reconnectInterval > 2000 && navigator.onLine) {
            _this.reconnectInterval = 2000;
        }
    }
}

Connection.prototype.send = function(data) {
    if (this.state !== 'connected') {
        console.trace('networkState is "' + this.state + '", can not send ' + data);
        return;
    }
    uni.sendSocketMessage({
        data: data
    });
}

Connection.prototype.close = function(){
    this.updateNetworkState('disconnected');
    uni.closeSocket();
}

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) {d[p] = b[p];}
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

function Channel(connection, channel_name) {
    this.subscribed = false;
    this.dispatcher = new Dispatcher();
    this.connection = connection;
    this.channelName = channel_name;
    this.subscribeCb = null;
    this.queue = [];
    __extends(this, this.dispatcher);
    var properies = ['on', 'off', 'emit'];
    for (var i in properies) {
        this[properies[i]] = this.dispatcher[properies[i]];
    }
}

Channel.prototype.processSubscribe = function () {
    if (this.connection.state !== 'connected') {
        return;
    }
    this.subscribeCb();
};

Channel.prototype.processQueue = function () {
    if (this.connection.state !== 'connected' || !this.subscribed) {
        return;
    }
    for (var i in this.queue) {
        this.queue[i]();
    }
    this.queue = [];
};

Channel.prototype.trigger = function (event, data) {
    if (event.indexOf('client-') !== 0) {
        throw new Error("Event '" + event + "' should start with 'client-'");
    }
    var _this = this;
    this.queue.push(function () {
        _this.connection.send(JSON.stringify({ event: event, data: data, channel: _this.channelName }));
    });
    this.processQueue();
};

////////////////
var Collections = (function () {
    var exports = {};
    function extend(target) {
        var sources = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            sources[_i - 1] = arguments[_i];
        }
        for (var i = 0; i < sources.length; i++) {
            var extensions = sources[i];
            for (var property in extensions) {
                if (extensions[property] && extensions[property].constructor &&
                    extensions[property].constructor === Object) {
                    target[property] = extend(target[property] || {}, extensions[property]);
                }
                else {
                    target[property] = extensions[property];
                }
            }
        }
        return target;
    }

    exports.extend = extend;
    function stringify() {
        var m = ["Push"];
        for (var i = 0; i < arguments.length; i++) {
            if (typeof arguments[i] === "string") {
                m.push(arguments[i]);
            }
            else {
                m.push(safeJSONStringify(arguments[i]));
            }
        }
        return m.join(" : ");
    }

    exports.stringify = stringify;
    function arrayIndexOf(array, item) {
        var nativeIndexOf = Array.prototype.indexOf;
        if (array === null) {
            return -1;
        }
        if (nativeIndexOf && array.indexOf === nativeIndexOf) {
            return array.indexOf(item);
        }
        for (var i = 0, l = array.length; i < l; i++) {
            if (array[i] === item) {
                return i;
            }
        }
        return -1;
    }

    exports.arrayIndexOf = arrayIndexOf;
    function objectApply(object, f) {
        for (var key in object) {
            if (Object.prototype.hasOwnProperty.call(object, key)) {
                f(object[key], key, object);
            }
        }
    }

    exports.objectApply = objectApply;
    function keys(object) {
        var keys = [];
        objectApply(object, function (_, key) {
            keys.push(key);
        });
        return keys;
    }

    exports.keys = keys;
    function values(object) {
        var values = [];
        objectApply(object, function (value) {
            values.push(value);
        });
        return values;
    }

    exports.values = values;
    function apply(array, f, context) {
        for (var i = 0; i < array.length; i++) {
            f.call(context || (window), array[i], i, array);
        }
    }

    exports.apply = apply;
    function map(array, f) {
        var result = [];
        for (var i = 0; i < array.length; i++) {
            result.push(f(array[i], i, array, result));
        }
        return result;
    }

    exports.map = map;
    function mapObject(object, f) {
        var result = {};
        objectApply(object, function (value, key) {
            result[key] = f(value);
        });
        return result;
    }

    exports.mapObject = mapObject;
    function filter(array, test) {
        test = test || function (value) {
            return !!value;
        };
        var result = [];
        for (var i = 0; i < array.length; i++) {
            if (test(array[i], i, array, result)) {
                result.push(array[i]);
            }
        }
        return result;
    }

    exports.filter = filter;
    function filterObject(object, test) {
        var result = {};
        objectApply(object, function (value, key) {
            if ((test && test(value, key, object, result)) || Boolean(value)) {
                result[key] = value;
            }
        });
        return result;
    }

    exports.filterObject = filterObject;
    function flatten(object) {
        var result = [];
        objectApply(object, function (value, key) {
            result.push([key, value]);
        });
        return result;
    }

    exports.flatten = flatten;
    function any(array, test) {
        for (var i = 0; i < array.length; i++) {
            if (test(array[i], i, array)) {
                return true;
            }
        }
        return false;
    }

    exports.any = any;
    function all(array, test) {
        for (var i = 0; i < array.length; i++) {
            if (!test(array[i], i, array)) {
                return false;
            }
        }
        return true;
    }

    exports.all = all;
    function encodeParamsObject(data) {
        return mapObject(data, function (value) {
            if (typeof value === "object") {
                value = safeJSONStringify(value);
            }
            return encodeURIComponent(base64_1["default"](value.toString()));
        });
    }

    exports.encodeParamsObject = encodeParamsObject;
    function buildQueryString(data) {
        var params = filterObject(data, function (value) {
            return value !== undefined;
        });
        return map(flatten(encodeParamsObject(params)), util_1["default"].method("join", "=")).join("&");
    }

    exports.buildQueryString = buildQueryString;
    function decycleObject(object) {
        var objects = [], paths = [];
        return (function derez(value, path) {
            var i, name, nu;
            switch (typeof value) {
                case 'object':
                    if (!value) {
                        return null;
                    }
                    for (i = 0; i < objects.length; i += 1) {
                        if (objects[i] === value) {
                            return {$ref: paths[i]};
                        }
                    }
                    objects.push(value);
                    paths.push(path);
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                        nu = [];
                        for (i = 0; i < value.length; i += 1) {
                            nu[i] = derez(value[i], path + '[' + i + ']');
                        }
                    }
                    else {
                        nu = {};
                        for (name in value) {
                            if (Object.prototype.hasOwnProperty.call(value, name)) {
                                nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']');
                            }
                        }
                    }
                    return nu;
                case 'number':
                case 'string':
                case 'boolean':
                    return value;
            }
        }(object, '$'));
    }

    exports.decycleObject = decycleObject;
    function safeJSONStringify(source) {
        try {
            return JSON.stringify(source);
        }
        catch (e) {
            return JSON.stringify(decycleObject(source));
        }
    }

    exports.safeJSONStringify = safeJSONStringify;
    return exports;
})();

var Dispatcher = (function () {
    function Dispatcher(failThrough) {
        this.callbacks = new CallbackRegistry();
        this.global_callbacks = [];
        this.failThrough = failThrough;
    }
    Dispatcher.prototype.on = function (eventName, callback, context) {
        this.callbacks.add(eventName, callback, context);
        return this;
    };
    Dispatcher.prototype.on_global = function (callback) {
        this.global_callbacks.push(callback);
        return this;
    };
    Dispatcher.prototype.off = function (eventName, callback, context) {
        this.callbacks.remove(eventName, callback, context);
        return this;
    };
    Dispatcher.prototype.emit = function (eventName, data) {
        var i;
        for (i = 0; i < this.global_callbacks.length; i++) {
            this.global_callbacks[i](eventName, data);
        }
        var callbacks = this.callbacks.get(eventName);
        if (callbacks && callbacks.length > 0) {
            for (i = 0; i < callbacks.length; i++) {
                callbacks[i].fn.call(callbacks[i].context || (window), data);
            }
        }
        else if (this.failThrough) {
            this.failThrough(eventName, data);
        }
        return this;
    };
    return Dispatcher;
}());

var CallbackRegistry = (function () {
    function CallbackRegistry() {
        this._callbacks = {};
    }
    CallbackRegistry.prototype.get = function (name) {
        return this._callbacks[prefix(name)];
    };
    CallbackRegistry.prototype.add = function (name, callback, context) {
        var prefixedEventName = prefix(name);
        this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || [];
        this._callbacks[prefixedEventName].push({
            fn: callback,
            context: context
        });
    };
    CallbackRegistry.prototype.remove = function (name, callback, context) {
        if (!name && !callback && !context) {
            this._callbacks = {};
            return;
        }
        var names = name ? [prefix(name)] : Collections.keys(this._callbacks);
        if (callback || context) {
            this.removeCallback(names, callback, context);
        }
        else {
            this.removeAllCallbacks(names);
        }
    };
    CallbackRegistry.prototype.removeCallback = function (names, callback, context) {
        Collections.apply(names, function (name) {
            this._callbacks[name] = Collections.filter(this._callbacks[name] || [], function (oning) {
                return (callback && callback !== oning.fn) ||
                    (context && context !== oning.context);
            });
            if (this._callbacks[name].length === 0) {
                delete this._callbacks[name];
            }
        }, this);
    };
    CallbackRegistry.prototype.removeAllCallbacks = function (names) {
        Collections.apply(names, function (name) {
            delete this._callbacks[name];
        }, this);
    };
    return CallbackRegistry;
}());
function prefix(name) {
    return "_" + name;
}

function __ajax(options){
    options=options||{};
    options.type=(options.type||'GET').toUpperCase();
    options.dataType=options.dataType||'json';
    params=formatParams(options.data);

    var xhr;
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();
    }else{
        xhr=ActiveXObject('Microsoft.XMLHTTP');
    }

    xhr.onreadystatechange=function(){
        if(xhr.readyState === 4){
            var status=xhr.status;
            if(status>=200 && status<300){
                options.success&&options.success(xhr.responseText,xhr.responseXML);
            }else{
                options.error&&options.error(status);
            }
        }
    }

    if(options.type==='GET'){
        xhr.open('GET',options.url+'?'+params,true);
        xhr.send(null);
    }else if(options.type==='POST'){
        xhr.open('POST',options.url,true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(params);
    }
}

function formatParams(data){
    var arr=[];
    for(var name in data){
        arr.push(encodeURIComponent(name)+'='+encodeURIComponent(data[name]));
    }
    return arr.join('&');
}

export default Push


转载二(微信小程序专用):

function Push(options) {
    this.doNotConnect = 0;
    options = options || {};
    options.heartbeat  = options.heartbeat || 25000;
    options.pingTimeout = options.pingTimeout || 10000;
    this.config = options;
    this.uid = 0;
    this.channels = {};
    this.connection = null;
    this.pingTimeoutTimer = 0;
    Push.instances.push(this);
    this.createConnection();
  }
  
  Push.prototype.checkoutPing = function() {
    var _this = this;
    setTimeout(function () {
        if (_this.connection.state === 'connected') {
            _this.connection.send('{"event":"pusher:ping","data":{}}');
            if (_this.pingTimeoutTimer) {
                clearTimeout(_this.pingTimeoutTimer);
                _this.pingTimeoutTimer = 0;
            }
            _this.pingTimeoutTimer = setTimeout(function () {
                _this.connection.closeAndClean();
                if (!_this.connection.doNotConnect) {
                    _this.connection.waitReconnect();
                }
            }, _this.config.pingTimeout);
        }
    }, this.config.heartbeat);
  };
  
  Push.prototype.channel = function (name) {
    return this.channels.find(name);
  };
  Push.prototype.allChannels = function () {
    return this.channels.all();
  };
  Push.prototype.createConnection = function () {
    if (this.connection) {
        throw Error('Connection already exist');
    }
    var _this = this;
    var url = this.config.url;
    function updateSubscribed () {
        for (var i in _this.channels) {
            _this.channels[i].subscribed = false;
        }
    }
    this.connection = new Connection({
        url: url,
        app_key: this.config.app_key,
        onOpen: function () {
            _this.connection.state  = 'connecting';
            _this.checkoutPing();
        },
        onMessage: function(params) {
            if(_this.pingTimeoutTimer) {
                clearTimeout(_this.pingTimeoutTimer);
                _this.pingTimeoutTimer = 0;
            }
  
            params = JSON.parse(params.data);
            var event = params.event;
            var channel_name = params.channel;
  
            if (event === 'pusher:pong') {
                _this.checkoutPing();
                return;
            }
            if (event === 'pusher:error') {
                throw Error(params.data.message);
            }
            var data = JSON.parse(params.data), channel;
            if (event === 'pusher_internal:subscription_succeeded') {
                channel = _this.channels[channel_name];
                channel.subscribed = true;
                channel.processQueue();
                channel.emit('pusher:subscription_succeeded');
                return;
            }
            if (event === 'pusher:connection_established') {
                _this.connection.socket_id = data.socket_id;
                _this.connection.state = 'connected';
                _this.subscribeAll();
            }
            if (event.indexOf('pusher_internal') !== -1) {
                console.log("Event '"+event+"' not implement");
                return;
            }
            channel = _this.channels[channel_name];
            if (channel) {
                channel.emit(event, data);
            }
        },
        onClose: function () {
            updateSubscribed();
        },
        onError: function () {
            updateSubscribed();
        }
    });
  };
  Push.prototype.disconnect = function () {
    this.connection.doNotConnect = 1;
    this.connection.close();
  };
  
  Push.prototype.subscribeAll = function () {
    if (this.connection.state !== 'connected') {
        return;
    }
    for (var channel_name in this.channels) {
        //this.connection.send(JSON.stringify({event:"pusher:subscribe", data:{channel:channel_name}}));
        this.channels[channel_name].processSubscribe();
    }
  };
  
  Push.prototype.unsubscribe = function (channel_name) {
    if (this.channels[channel_name]) {
        delete this.channels[channel_name];
        if (this.connection.state === 'connected') {
            this.connection.send(JSON.stringify({event:"pusher:unsubscribe", data:{channel:channel_name}}));
        }
    }
  };
  Push.prototype.unsubscribeAll = function () {
    var channels = Object.keys(this.channels);
    if (channels.length) {
        if (this.connection.state === 'connected') {
            for (var channel_name in this.channels) {
                this.unsubscribe(channel_name);
            }
        }
    }
    this.channels = {};
  };
  Push.prototype.subscribe = function (channel_name) {
    if (this.channels[channel_name]) {
        return this.channels[channel_name];
    }
    if (channel_name.indexOf('private-') === 0) {
        return createPrivateChannel(channel_name, this);
    }
    if (channel_name.indexOf('presence-') === 0) {
        return createPresenceChannel(channel_name, this);
    }
    return createChannel(channel_name, this);
  };
  Push.instances = [];
  
  function createChannel(channel_name, push)
  {
    var channel = new Channel(push.connection, channel_name);
    push.channels[channel_name] = channel;
    channel.subscribeCb = function () {
        push.connection.send(JSON.stringify({event:"pusher:subscribe", data:{channel:channel_name}}));
    }
    return channel;
  }
  
  function createPrivateChannel(channel_name, push)
  {
    var channel = new Channel(push.connection, channel_name);
    push.channels[channel_name] = channel;
    channel.subscribeCb = function () {
        __ajax({
            url: push.config.auth,
            type: 'POST',
            data: {channel_name: channel_name, socket_id: push.connection.socket_id},
            success: function (data) {
                data = JSON.parse(data);
                data.channel = channel_name;
                push.connection.send(JSON.stringify({event:"pusher:subscribe", data:data}));
            },
            error: function (e) {
                throw Error(e);
            }
        });
    };
    channel.processSubscribe();
    return channel;
  }
  
  function createPresenceChannel(channel_name, push)
  {
    return createPrivateChannel(channel_name, push);
  }
  
  /*window.addEventListener('online',  function(){
    var con;
    for (var i in Push.instances) {
        con = Push.instances[i].connection;
        con.reconnectInterval = 1;
        if (con.state === 'connecting') {
            con.connect();
        }
    }
  });*/
  
  
  function Connection(options) {
    this.dispatcher = new Dispatcher();
    __extends(this, this.dispatcher);
    var properies = ['on', 'off', 'emit'];
    for (var i in properies) {
        this[properies[i]] = this.dispatcher[properies[i]];
    }
    this.options = options;
    this.state = 'initialized'; //initialized connecting connected disconnected
    this.doNotConnect = 0;
    this.reconnectInterval = 1;
    this.connection = null;
    this.reconnectTimer = 0;
    this.connect();
  }
  
  Connection.prototype.updateNetworkState = function(state){
    var old_state = this.state;
    this.state = state;
    if (old_state !== state) {
        this.emit('state_change', { previous: old_state, current: state });
    }
  };
  
  Connection.prototype.connect = function () {
    this.doNotConnect = 0;
    if (this.networkState == 'connecting' || this.networkState == 'established') {
        console.log('networkState is ' + this.networkState + ' and do not need connect');
        return;
    }
    if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = 0;
    }
  
    this.closeAndClean();
  
    var options = this.options;
    var _this = this;
    _this.updateNetworkState('connecting');
    var cb = function(){
         wx.onSocketOpen(function (res) {
            _this.reconnectInterval = 1;
            if (_this.doNotConnect) {
                _this.updateNetworkState('closing');
                wx.closeSocket();
                return;
            }
            _this.updateNetworkState('established');
            if (options.onOpen) {
                options.onOpen(res);
            }
        });
  
        if (options.onMessage) {
            wx.onSocketMessage(options.onMessage);
        }
  
        wx.onSocketClose(function (res) {
            _this.updateNetworkState('disconnected');
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onClose) {
                options.onClose(res);
            }
        });
  
        wx.onSocketError(function (res) {
            _this.close();
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onError) {
                options.onError(res);
            }
        });
    };
    wx.connectSocket({
        url: options.url,
        fail: function (res) {
            console.log('wx.connectSocket fail');
            console.log(res);
            _this.updateNetworkState('disconnected');
            _this.waitReconnect();
        },
        success: function() {
  
        }
    });
    cb();
  }
  
  Connection.prototype.connect = function () {
    this.doNotConnect = 0;
    if (this.state === 'connected') {
        console.log('networkState is "' + this.state + '" and do not need connect');
        return;
    }
    if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = 0;
    }
  
    this.closeAndClean();
  
    var options = this.options;
  
    this.updateNetworkState('connecting');
  
    var _this = this;
    var cb = function(){
         wx.onSocketOpen(function (res) {
            _this.reconnectInterval = 1;
            if (_this.doNotConnect) {
                _this.updateNetworkState('disconnected');
                wx.closeSocket();
                return;
            }
            if (options.onOpen) {
                options.onOpen(res);
            }
        });
  
        if (options.onMessage) {
            wx.onSocketMessage(options.onMessage);
        }
  
        wx.onSocketClose(function (res) {
            _this.updateNetworkState('disconnected');
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onClose) {
                options.onClose(res);
            }
        });
  
        wx.onSocketError(function (res) {
            _this.close();
            if (!_this.doNotConnect) {
                _this.waitReconnect();
            }
            if (options.onError) {
                options.onError(res);
            }
        });
    };
    wx.connectSocket({
        url: options.url+'/app/'+options.app_key,
        fail: function (res) {
            console.log('wx.connectSocket fail');
            console.log(res);
            _this.updateNetworkState('disconnected');
            _this.waitReconnect();
        },
        success: function() {
  
        }
    });
    cb();
  }
  
  Connection.prototype.closeAndClean = function () {
    if (this.state === 'connected') {
        wx.closeSocket();
    }
    this.updateNetworkState('disconnected');
  };
  
  Connection.prototype.waitReconnect = function () {
    if (this.state === 'connected' || this.state === 'connecting') {
        return;
    }
    if (!this.doNotConnect) {
        this.updateNetworkState('connecting');
        var _this = this;
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
        }
        this.reconnectTimer = setTimeout(function(){
            _this.connect();
        }, this.reconnectInterval);
        if (this.reconnectInterval < 1000) {
            this.reconnectInterval = 1000;
        } else {
            // 每次重连间隔增大一倍
            this.reconnectInterval = this.reconnectInterval * 2;
        }

        let online = false;
        wx.getNetworkType({
            success (res) {
              console.log(res)
              if(res.networkType !== 'none'){
                online = true;
              }
            }
        })
        // 有网络的状态下,重连间隔最大2秒
        if (this.reconnectInterval > 2000 && online) {
            _this.reconnectInterval = 2000;
        }
    }
  }
  
  Connection.prototype.send = function(data) {
    if (this.state !== 'connected') {
        console.trace('networkState is "' + this.state + '", can not send ' + data);
        return;
    }
    wx.sendSocketMessage({
        data: data
    });
  }
  
  Connection.prototype.close = function(){
    this.updateNetworkState('disconnected');
    wx.closeSocket();
  }
  
  var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) {d[p] = b[p];}
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  
  function Channel(connection, channel_name) {
    this.subscribed = false;
    this.dispatcher = new Dispatcher();
    this.connection = connection;
    this.channelName = channel_name;
    this.subscribeCb = null;
    this.queue = [];
    __extends(this, this.dispatcher);
    var properies = ['on', 'off', 'emit'];
    for (var i in properies) {
        this[properies[i]] = this.dispatcher[properies[i]];
    }
  }
  
  Channel.prototype.processSubscribe = function () {
    if (this.connection.state !== 'connected') {
        return;
    }
    this.subscribeCb();
  };
  
  Channel.prototype.processQueue = function () {
    if (this.connection.state !== 'connected' || !this.subscribed) {
        return;
    }
    for (var i in this.queue) {
        this.queue[i]();
    }
    this.queue = [];
  };
  
  Channel.prototype.trigger = function (event, data) {
    if (event.indexOf('client-') !== 0) {
        throw new Error("Event '" + event + "' should start with 'client-'");
    }
    var _this = this;
    this.queue.push(function () {
        _this.connection.send(JSON.stringify({ event: event, data: data, channel: _this.channelName }));
    });
    this.processQueue();
  };
  
  ////////////////
  var Collections = (function () {
    var exports = {};
    function extend(target) {
        var sources = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            sources[_i - 1] = arguments[_i];
        }
        for (var i = 0; i < sources.length; i++) {
            var extensions = sources[i];
            for (var property in extensions) {
                if (extensions[property] && extensions[property].constructor &&
                    extensions[property].constructor === Object) {
                    target[property] = extend(target[property] || {}, extensions[property]);
                }
                else {
                    target[property] = extensions[property];
                }
            }
        }
        return target;
    }
  
    exports.extend = extend;
    function stringify() {
        var m = ["Push"];
        for (var i = 0; i < arguments.length; i++) {
            if (typeof arguments[i] === "string") {
                m.push(arguments[i]);
            }
            else {
                m.push(safeJSONStringify(arguments[i]));
            }
        }
        return m.join(" : ");
    }
  
    exports.stringify = stringify;
    function arrayIndexOf(array, item) {
        var nativeIndexOf = Array.prototype.indexOf;
        if (array === null) {
            return -1;
        }
        if (nativeIndexOf && array.indexOf === nativeIndexOf) {
            return array.indexOf(item);
        }
        for (var i = 0, l = array.length; i < l; i++) {
            if (array[i] === item) {
                return i;
            }
        }
        return -1;
    }
  
    exports.arrayIndexOf = arrayIndexOf;
    function objectApply(object, f) {
        for (var key in object) {
            if (Object.prototype.hasOwnProperty.call(object, key)) {
                f(object[key], key, object);
            }
        }
    }
  
    exports.objectApply = objectApply;
    function keys(object) {
        var keys = [];
        objectApply(object, function (_, key) {
            keys.push(key);
        });
        return keys;
    }
  
    exports.keys = keys;
    function values(object) {
        var values = [];
        objectApply(object, function (value) {
            values.push(value);
        });
        return values;
    }
  
    exports.values = values;
    function apply(array, f, context) {
        for (var i = 0; i < array.length; i++) {
            f.call(context || (window), array[i], i, array);
        }
    }
  
    exports.apply = apply;
    function map(array, f) {
        var result = [];
        for (var i = 0; i < array.length; i++) {
            result.push(f(array[i], i, array, result));
        }
        return result;
    }
  
    exports.map = map;
    function mapObject(object, f) {
        var result = {};
        objectApply(object, function (value, key) {
            result[key] = f(value);
        });
        return result;
    }
  
    exports.mapObject = mapObject;
    function filter(array, test) {
        test = test || function (value) {
            return !!value;
        };
        var result = [];
        for (var i = 0; i < array.length; i++) {
            if (test(array[i], i, array, result)) {
                result.push(array[i]);
            }
        }
        return result;
    }
  
    exports.filter = filter;
    function filterObject(object, test) {
        var result = {};
        objectApply(object, function (value, key) {
            if ((test && test(value, key, object, result)) || Boolean(value)) {
                result[key] = value;
            }
        });
        return result;
    }
  
    exports.filterObject = filterObject;
    function flatten(object) {
        var result = [];
        objectApply(object, function (value, key) {
            result.push([key, value]);
        });
        return result;
    }
  
    exports.flatten = flatten;
    function any(array, test) {
        for (var i = 0; i < array.length; i++) {
            if (test(array[i], i, array)) {
                return true;
            }
        }
        return false;
    }
  
    exports.any = any;
    function all(array, test) {
        for (var i = 0; i < array.length; i++) {
            if (!test(array[i], i, array)) {
                return false;
            }
        }
        return true;
    }
  
    exports.all = all;
    function encodeParamsObject(data) {
        return mapObject(data, function (value) {
            if (typeof value === "object") {
                value = safeJSONStringify(value);
            }
            return encodeURIComponent(base64_1["default"](value.toString()));
        });
    }
  
    exports.encodeParamsObject = encodeParamsObject;
    function buildQueryString(data) {
        var params = filterObject(data, function (value) {
            return value !== undefined;
        });
        return map(flatten(encodeParamsObject(params)), util_1["default"].method("join", "=")).join("&");
    }
  
    exports.buildQueryString = buildQueryString;
    function decycleObject(object) {
        var objects = [], paths = [];
        return (function derez(value, path) {
            var i, name, nu;
            switch (typeof value) {
                case 'object':
                    if (!value) {
                        return null;
                    }
                    for (i = 0; i < objects.length; i += 1) {
                        if (objects[i] === value) {
                            return {$ref: paths[i]};
                        }
                    }
                    objects.push(value);
                    paths.push(path);
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                        nu = [];
                        for (i = 0; i < value.length; i += 1) {
                            nu[i] = derez(value[i], path + '[' + i + ']');
                        }
                    }
                    else {
                        nu = {};
                        for (name in value) {
                            if (Object.prototype.hasOwnProperty.call(value, name)) {
                                nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']');
                            }
                        }
                    }
                    return nu;
                case 'number':
                case 'string':
                case 'boolean':
                    return value;
            }
        }(object, '$'));
    }
  
    exports.decycleObject = decycleObject;
    function safeJSONStringify(source) {
        try {
            return JSON.stringify(source);
        }
        catch (e) {
            return JSON.stringify(decycleObject(source));
        }
    }
  
    exports.safeJSONStringify = safeJSONStringify;
    return exports;
  })();
  
  var Dispatcher = (function () {
    function Dispatcher(failThrough) {
        this.callbacks = new CallbackRegistry();
        this.global_callbacks = [];
        this.failThrough = failThrough;
    }
    Dispatcher.prototype.on = function (eventName, callback, context) {
        this.callbacks.add(eventName, callback, context);
        return this;
    };
    Dispatcher.prototype.on_global = function (callback) {
        this.global_callbacks.push(callback);
        return this;
    };
    Dispatcher.prototype.off = function (eventName, callback, context) {
        this.callbacks.remove(eventName, callback, context);
        return this;
    };
    Dispatcher.prototype.emit = function (eventName, data) {
        var i;
        for (i = 0; i < this.global_callbacks.length; i++) {
            this.global_callbacks[i](eventName, data);
        }
        var callbacks = this.callbacks.get(eventName);
        if (callbacks && callbacks.length > 0) {
            for (i = 0; i < callbacks.length; i++) {
                callbacks[i].fn.call(callbacks[i].context || (window), data);
            }
        }
        else if (this.failThrough) {
            this.failThrough(eventName, data);
        }
        return this;
    };
    return Dispatcher;
  }());
  
  var CallbackRegistry = (function () {
    function CallbackRegistry() {
        this._callbacks = {};
    }
    CallbackRegistry.prototype.get = function (name) {
        return this._callbacks[prefix(name)];
    };
    CallbackRegistry.prototype.add = function (name, callback, context) {
        var prefixedEventName = prefix(name);
        this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || [];
        this._callbacks[prefixedEventName].push({
            fn: callback,
            context: context
        });
    };
    CallbackRegistry.prototype.remove = function (name, callback, context) {
        if (!name && !callback && !context) {
            this._callbacks = {};
            return;
        }
        var names = name ? [prefix(name)] : Collections.keys(this._callbacks);
        if (callback || context) {
            this.removeCallback(names, callback, context);
        }
        else {
            this.removeAllCallbacks(names);
        }
    };
    CallbackRegistry.prototype.removeCallback = function (names, callback, context) {
        Collections.apply(names, function (name) {
            this._callbacks[name] = Collections.filter(this._callbacks[name] || [], function (oning) {
                return (callback && callback !== oning.fn) ||
                    (context && context !== oning.context);
            });
            if (this._callbacks[name].length === 0) {
                delete this._callbacks[name];
            }
        }, this);
    };
    CallbackRegistry.prototype.removeAllCallbacks = function (names) {
        Collections.apply(names, function (name) {
            delete this._callbacks[name];
        }, this);
    };
    return CallbackRegistry;
  }());
  function prefix(name) {
    return "_" + name;
  }
  
  function __ajax(options){
    options=options||{};
    options.type=(options.type||'GET').toUpperCase();
    options.dataType=options.dataType||'json';
    params=formatParams(options.data);
  
    var xhr;
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();
    }else{
        xhr=ActiveXObject('Microsoft.XMLHTTP');
    }
  
    xhr.onreadystatechange=function(){
        if(xhr.readyState === 4){
            var status=xhr.status;
            if(status>=200 && status<300){
                options.success&&options.success(xhr.responseText,xhr.responseXML);
            }else{
                options.error&&options.error(status);
            }
        }
    }
  
    if(options.type==='GET'){
        xhr.open('GET',options.url+'?'+params,true);
        xhr.send(null);
    }else if(options.type==='POST'){
        xhr.open('POST',options.url,true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(params);
    }
  }
  
  function formatParams(data){
    var arr=[];
    for(var name in data){
        arr.push(encodeURIComponent(name)+'='+encodeURIComponent(data[name]));
    }
    return arr.join('&');
  }
  
  export default Push


为了不迷路,特意转载:
https://www.workerman.net/q/11532
https://github.com/ljnchn/push/tree/main/src
webman插件:
https://www.workerman.net/plugin/2

如题:

  "tab":{
    enable": false
    keepstatetrue.session": truepreload": false,max":"30"
    "index":{
      "id":"@"
      "href":"/app/admin/index/dashboard""title":"仪表盘,
    }
  }

注意:把这里关了tab,再写height:'full-xx' 就可以了。

一、打开:phpStudy v8.0,网站-创建网站-https

1112019092632837853.png

二 、导入SSL证书

2222019092633165211.png
登录邮箱下载:Gworg证书文件目录 ,都会有以下五个文件夹。

文件说明
1_root_bundle.crt 证书链文件(*chain.crt)
2_star_gworg_com.crt 公钥文件(*.crt)
3_star_gworg_com.key 私钥文件(*key)

3332019092632884665.png
测试学习:可以直接点击:生成开发者测试证书

注:由于证书是未认证的证书,所以不受浏览器信任,会显示为不安全的证书,我们可以通过设置信任证书或者直接点击高级,继续前往就能使用)

注意事项:

一、服务器windows防火墙允许443端口

二、云服务器需要单独在控制面板设置允许443端口,教程:云服务器安全组添加443 80 21 22端口阿里云腾讯云华为云教程

(完)

本文转自:
https://www.gworg.com/ssl/1157.html
https://www.gworg.com/ssl/71.html

在操作数据库时,客户端提示如下错误:

MySQL5.7.26错误问题 mysqld.exe: Error while setting value 'STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER, NO_ENGINE_SUBSTITUTION' to 'sql_mode'

这样的问题出现,是因为MySQL的配置文件my.ini中sql_mode的值,逗号后面加上了空格导致的无法启动,需要手动删除空格就可以了。

通过谷歌搜索了一下,找到了最终的解决方案,如下:

my.ini原来部分代码:

tmp_table_size=64M
wait_timeout=120
sql_mode=STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER, NO_ENGINE_SUBSTITUTION

[client]
port=3306
default-character-set=utf8

my.ini修改后代码:

tmp_table_size=64M
wait_timeout=120
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

[client]
port=3306
default-character-set=utf8

最后,重启即可。

修改前后的比对提示,如下图:
QQ20230906-081119@2x.png

本文转自:https://xinyufeng.net/2022/03/28/

通常提示为:无法启动此程序,因为计算机中丢失VCRUNTIME140.dll,尝试重新安装此程序以解决此问题方案合集。

如下图所示:
QQ20230906-075748@2x.png

网上有许多种解决办法,但最安全有效的办法就是安装微软的C++程序集。

第一步:网盘下载微软的安装程包.exe

链接: https://pan.baidu.com/s/1RObq8NIB40YXZRhCmz4iaA 
提取码: fmyv


第二步:下一步下一步即可,连重启都不用。

QQ20230906-080010@2x.png

最后,就安装完成,问题解决。

表现为:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tlslyzx_com.xf_orders.pay_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

解决办法:

SELECT @@sql_mode;
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
SELECT @@sql_mode;





一、升级前准备

以下是tp6.1.x升级到tp8.0.x的步骤,如果你目前版本是tp6.0.x的,请先将期升级到tp6.1.x切记!!

6.0升级到6.1版本
由于安全性原因,6.1版本移除核心对think-filesystem库的依赖,因此6.0版本升级至6.1版本后,需要单独安装`topthink/think-filesystem`库。

二、查看PHP的版本,tp8要求php >= 8.0

1、查看php版本:

liuhongdi@lhdpc:~$ /usr/local/soft/php8/bin/php --version
PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies

当前版本是 8.1.1 ,显然符合条件

2、查看当前项止的thinkphp版本:

liuhongdi@lhdpc:/data/php/tpapibase$ php think version
v6.1.0

三、升级ThinkPHP开始

1、升级原项目到可用的最新版本:

liuhongdi@lhdpc:/data/php/tpapibase$ composer update topthink/framework
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 1 update, 0 removals
  - Upgrading topthink/framework (v6.1.1 => v6.1.4)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Downloading topthink/framework (v6.1.4)
  - Upgrading topthink/framework (v6.1.1 => v6.1.4): Extracting archive
Generating autoload files
> @php think service:discover
Succeed!
> @php think vendor:publish
File /data/php/tpapibase/config/trace.php exist!
Succeed!
4 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found
liuhongdi@lhdpc:/data/php/tpapibase$ php think version
v6.1.4

可以看到升级完成后版本是v6.1.4

2、修改composer.json

"require": {
        "php": ">=8.0.0",
        "topthink/framework": "^8.0",
        "topthink/think-orm": "^3.0",
        "topthink/think-filesystem": "^2.0"
    },
    "require-dev": {
        "symfony/var-dumper": ">=4.2",
        "topthink/think-trace":"^1.0"
    },

对require需要用到的库的版本调整,我的配置版本号如上,

“topthink/think-filesystem”: “^2.0”, 这一行是我手动添加上的,

说明:这些版本号是从哪里来的?

用下面的命令新创建一个thinkphp8项目,从composer.json中就看到了

liuhongdi@lhdpc:/data/php$ composer create-project topthink/think tp8

3、删除composer.lock

liuhongdi@lhdpc:/data/php/tpapibase$ rm composer.lock

4、升级前查看当前各库的版本:

liuhongdi@lhdpc:/data/php/tpapibase$ composer show
firebase/php-jwt          v6.3.1  A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.
psr/container             1.1.2   Common Container Interface (PHP FIG PSR-11)
psr/http-message          1.0.1   Common interface for HTTP messages
psr/log                   1.1.4   Common interface for logging libraries
psr/simple-cache          1.0.1   Common interfaces for simple caching
symfony/polyfill-mbstring v1.27.0 Symfony polyfill for the Mbstring extension
symfony/polyfill-php72    v1.27.0 Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions
symfony/polyfill-php80    v1.27.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/var-dumper        v4.4.47 Provides mechanisms for walking through any arbitrary PHP variable
topthink/framework        v6.1.4  The ThinkPHP Framework.
topthink/think-helper     v3.1.6  The ThinkPHP6 Helper Package
topthink/think-orm        v2.0.56 think orm
topthink/think-trace      v1.5    thinkphp debug trace

5、升级:

liuhongdi@lhdpc:/data/php/tpapibase$ composer install
No composer.lock file present. Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.
Loading composer repositories with package information
Updating dependencies
Lock file operations: 14 installs, 0 updates, 0 removals
  - Locking firebase/php-jwt (v6.8.0)
  - Locking league/flysystem (2.5.0)
  - Locking league/mime-type-detection (1.11.0)
  - Locking psr/container (2.0.2)
  - Locking psr/http-message (1.1)
  - Locking psr/log (3.0.0)
  - Locking psr/simple-cache (3.0.0)
  - Locking symfony/polyfill-mbstring (v1.27.0)
  - Locking symfony/var-dumper (v6.3.0)
  - Locking topthink/framework (v8.0.1)
  - Locking topthink/think-filesystem (v2.0.2)
  - Locking topthink/think-helper (v3.1.6)
  - Locking topthink/think-orm (v3.0.11)
  - Locking topthink/think-trace (v1.6)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 3 installs, 6 updates, 2 removals
  - Downloading league/mime-type-detection (1.11.0)
  - Downloading psr/container (2.0.2)
  - Downloading symfony/var-dumper (v6.3.0)
  - Downloading psr/simple-cache (3.0.0)
  - Downloading psr/log (3.0.0)
  - Downloading topthink/think-orm (v3.0.11)
  - Downloading topthink/framework (v8.0.1)
  - Downloading league/flysystem (2.5.0)
  - Downloading topthink/think-filesystem (v2.0.2)
  - Removing symfony/polyfill-php80 (v1.27.0)
  - Removing symfony/polyfill-php72 (v1.27.0)
  - Installing league/mime-type-detection (1.11.0): Extracting archive
  - Upgrading psr/container (1.1.2 => 2.0.2): Extracting archive
  - Upgrading symfony/var-dumper (v4.4.47 => v6.3.0): Extracting archive
  - Upgrading psr/simple-cache (1.0.1 => 3.0.0): Extracting archive
  - Upgrading psr/log (1.1.4 => 3.0.0): Extracting archive
  - Upgrading topthink/think-orm (v2.0.61 => v3.0.11): Extracting archive
  - Upgrading topthink/framework (v6.1.4 => v8.0.1): Extracting archive
  - Installing league/flysystem (2.5.0): Extracting archive
  - Installing topthink/think-filesystem (v2.0.2): Extracting archive
2 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
> @php think service:discover
Succeed!
> @php think vendor:publish
File /data/php/tpapibase/config/trace.php exist!
Succeed!
4 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

6、查看升级后的版本:

liuhongdi@lhdpc:/data/php/tpapibase$ composer show
firebase/php-jwt           v6.8.0  A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.
league/flysystem           2.5.0   File storage abstraction for PHP
league/mime-type-detection 1.11.0  Mime-type detection for Flysystem
psr/container              2.0.2   Common Container Interface (PHP FIG PSR-11)
psr/http-message           1.1     Common interface for HTTP messages
psr/log                    3.0.0   Common interface for logging libraries
psr/simple-cache           3.0.0   Common interfaces for simple caching
symfony/polyfill-mbstring  v1.27.0 Symfony polyfill for the Mbstring extension
symfony/var-dumper         v6.3.0  Provides mechanisms for walking through any arbitrary PHP variable
topthink/framework         v8.0.1  The ThinkPHP Framework.
topthink/think-filesystem  v2.0.2  The ThinkPHP6.1 Filesystem Package
topthink/think-helper      v3.1.6  The ThinkPHP6 Helper Package
topthink/think-orm         v3.0.11 the PHP Database&ORM Framework
topthink/think-trace       v1.6    thinkphp debug trace

7、用php命令查看版本:

liuhongdi@lhdpc:/data/php/tpapibase$ php think version
v8.0.0


最后:

需要注意的是,与之相关的扩展也需要一同更新,比如:composer require topthink/think-view否则会出现报错,如:Call to undefined method....

转自:https://www.cnblogs.com/architectforest/p/17584818.html

不同的签名验签代码,对密钥格式有不同的要求:

比如JAVA一般使用PKCS8格式的密钥,其他语言一般使用PKCS1格式的密钥。

区分小技巧:

开头为"-----BEGIN PRIVATE KEY-----"的密钥格式为PKCS8,
开头为"-----BEGIN RSA PRIVATE KEY-----"的密钥格式为PKCS1

1、数据库连接改为 mysqli
2、connect.php文件里常量 MAGIC_QUOTES_GPC改为如下

define('MAGIC_QUOTES_GPC', version_compare(PHP_VERSION, '5.6.40') > 0 ? false : function_exists('get_magic_quotes_gpc')&&get_magic_quotes_gpc());

3、关闭所以错误报告

注意:
7.5新版安装前改以下文件即可
e/class/connect.php

define('MAGIC_QUOTES_GPC',function_exists('get_magic_quotes_gpc')&&get_magic_quotes_gpc());

改为:

define('MAGIC_QUOTES_GPC',(ini_get('magic_quotes_gpc') == 1) ? true : false);

说明:get_magic_quotes_gpc()php5.4版之后已废除了。

注意三点:

1、交叉编译,要把我的 go 代码编译为 window 执行的文件
2、编译 html 等静态文件到 exe 文件中
3、启动 window 的浏览器

package main
import (
    _ "embed"
    "log"
    "net"
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/skratchdot/open-golang/open"
)
// 这里不能有空格
//go:embed templates/transaction.html
var content []byte

func main() {
    l, err := net.Listen("tcp", "localhost:3000")
    if err != nil {
        log.Fatal(err)
    }
    r := SetRouter()

    // 使用第三方的包打开chrome
    open.RunWith("http://localhost:3000/transaction", "chrome")
    // Start the blocking server loop
    http.Serve(l, r)
}

func SetRouter() *gin.Engine {
    r := gin.Default()
    // 显示发起交易页面
    r.GET("/transaction", func(c *gin.Context) {
        c.Data(http.StatusOK, "text/html", content)
    })
    return r
}

交叉编译

Linux 下编译 Mac 和 Windows 64 位可执行程序

CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Mac 下编译 Linux 和 Windows 64 位可执行程序

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Windows 下编译,依次执行如下命令

SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build -o goblog

通过如下命令可查看 Go 支持 OS 和平台列表:

go tool dist list
aix/ppc64
android/386
android/amd64
android/arm
android/arm64
darwin/amd64
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
freebsd/arm64
illumos/amd64
ios/amd64
ios/arm64
js/wasm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/mips
linux/mips64
.
.
.
windows/386
windows/amd64
windows/arm
windows/arm64

参考编辑:https://learnku.com/articles/70273?#reply275739