话不多说,直接上代码,, websocket 可以实现的东西有很多,,,可以广播式的无差别推送,,,也可以实现点对点的沟通,,,网页版的聊天对话 以下是 在客户端方面的配置
$(document).ready(function () {
chinaTv();
});
var reconnect = 0;
function chinaTv() {
var ws = new WebSocket("链接地址");
var lineCount = 0;
var colHeadings = [];
ws.onerror = function(e) {
console.log(e);
};
ws.onopen = function() {
console.log('connect');
lineCount = 0;
};
ws.onclose = function() {
console.log('disconnect');
if(reconnect < 360){
setTimeout("chinaTv()", 10000);
reconnect++;
}else{
alert('业绩播报发生错误,请联系技术同学!!');
}
};
ws.onmessage = function(e) {
console.log('这里是推送过来的信息,处理的地方');
};
}
在服务端,主要来介绍一下参数的设置
protected static $aWSServOptions = array(
'worker_num' => 10,
'daemonize' => true,
'max_request' => 100000,
'log_file' => '/data1/logs/websocket.error.log',
);
我们用的版本比较古老,, 韩天峰大佬说 建议升级版本,,,这个版本也太古老了点,,, 我们遇到的问题就是,,推送会陷入死循环,,疯狂推入给客户端,导致客户端卡死,,, 参考文档链接https://www.kancloud.cn/oydm360782/swoole/44571 下面是我们自己的问题代码
WebSocketServBase::$oWebSocketServ->on('start', function ( $oServ ){
WebSocketServBase::setPidFile( $oServ->master_pid, 'message' );
swoole_event_add(WebSocketServBase::$oServProcess->pipe, function() use ( $oServ ) {
$sData = WebSocketServBase::$oServProcess->read();
$iStartfd = 0;
while (true){
$aConnLists = $oServ->connection_list($iStartfd);
p(implode(',',$aConnLists));
if ( empty($aConnLists) ){
echo date("Y-m-d H:i:s").' push finished'.PHP_EOL;
break;
}
foreach($aConnLists as $fd) {
$iStartfd = $fd + 1;
if ( $oServ->getClientInfo($fd)['websocket_status'] == 0 ) continue;
$oServ->push($fd, $sData);
}
}
WebSocketServBase::$oServProcess->exit(0);
});
});
解决方案: 这里的解决方案有点粗暴,,就是在这里直接控制了推送的数量,,连接的客户端超过了 100 ,那就对不起了,你可能连上了,,收不到推送,,嘿嘿,,
WebSocketServBase::$oWebSocketServ->on('start', function ( $oServ ){
WebSocketServBase::setPidFile( $oServ->master_pid, 'message' );
swoole_event_add(WebSocketServBase::$oServProcess->pipe, function() use ( $oServ ) {
$sData = WebSocketServBase::$oServProcess->read();
$aConnLists = $oServ->connection_list(0,100);
if ( empty($aConnLists) ){
echo date("Y-m-d H:i:s").' push finished'.PHP_EOL;
return 0;
}
$console = date("Y-m-d H:i:s").' - connect: '.implode(',',$aConnLists).' - push: ';
foreach($aConnLists as $fd) {
$iStartfd = $fd + 1;
if ( $oServ->getClientInfo($fd)['websocket_status'] == 0 ) continue;
$oServ->push($fd, $sData);
$console .= $fd.' ';
}
$console .= "- message: ".$sData;
echo _green($console).PHP_EOL;
});
});
|