websocket.php 2.2 KB
<?php
use yii\web\View;
use yii\helpers\ArrayHelper;

$this->registerJsFile('/js/php.js',array('postion'=>View::POS_END));
$this->registerJsFile('/js/common.js',array('position'=>View::POS_END));
?>

<?php
//推送服务地址
$wsAddrs = (new \common\models\SysConfig)->getServerAddr();
$wsAddr = @ArrayHelper::getValue($wsAddrs, ['websocket',0]);
?>

<script type="text/javascript">
<?php $this->beginBlock('javascript');?>
var socket_arr = '<?=$wsAddr?>'.split(":");
var wsAddr = socket_arr[0];
var port = socket_arr[1];

/**
 * websocket推送指令
 * @returns {undefined}
 */
function callWebsocket(sendCallback,afterSendCallback = function(){},errorSendCallback = function(){}){
    if (!window.ws || window.ws.readyState === undefined || window.ws.readyState != 1) {
        websocket(wsAddr,port,'/',function(){
            consoleLog('连接服务器'+wsAddr+':'+port);
            
            sendCallback();
        },function(evt){
            consoleLog('收到消息: '+evt.data);
            data = JSON.parse(evt.data);
            if (data.status == 1){
                consoleLog('请求推送成功');
                afterSendCallback();
            }else{
                consoleLog('请求推送失败');
                errorSendCallback();
            }
        },function(){
            consoleLog('连接已关闭');
        },function(){
            consoleLog('有错误出现');
        });
    }else{
        sendCallback();
    }
}
/**
 * 页面打印发送记录
 * @param {type} msg
 * @returns {undefined}
 */
function consoleLog(msg){
    if (msg){
        console.log(msg);
    }
    if ($('#wsRuntime').size()){
        $('#wsRuntime').append('&nbsp;'+msg+'<br />');
    }
}
/**
 * 密钥生成
 * @param {type} package
 * @returns {unresolved}
 */
function makeSign(package){
    package['private_key'] = 'a85bb0674e08986c6b115d5e3a4884fa';
    package = ksort(package);
    packageList = [];
    for (key in package){
        packageList.push(trim(key + '=' + package[key]));
    }
    package['secret'] =  strtolower(md5(implode('&', packageList)));
    delete(package['private_key']);
    return package;
}
<?php 
$this->endBlock();
$this->registerJs($this->blocks['javascript'],View::POS_END)
?>
</script>