websocket.php
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?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(' '+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>