VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 网站开发 > PHP >
  • php教程之基于workerman的实时推送(摒弃ajax轮询)(2)

  

其中,workerman里面的推送核心代码实现

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
// 全局数组保存uid在线数据
$uidConnectionMap = array();
// 记录最后一次广播的在线用户数
$last_online_count = 0;
  
  
// PHPSocketIO服务
$sender_io = new SocketIO(2120);
// 客户端发起连接事件时,设置连接socket的各种事件回调
  
// 当$sender_io启动后监听一个http端口,通过这个端口可以给任意uid或者所有uid推送数据
$sender_io->on('workerStart', function(){
 // 监听一个http端口
 $inner_http_worker = new Worker('http://0.0.0.0:2121');
 // 当http客户端发来数据时触发
 $inner_http_worker->onMessage = function($http_connection, $data){
 global $uidConnectionMap;
 $_POST = $_POST ? $_POST : $_GET;
 // 推送数据的url格式 type=publish&to=uid&content=xxxx
 switch(@$_POST['type']){
 case 'publish':
 global $sender_io;
 $to = @$_POST['to'];
 $_POST['content'] = htmlspecialchars(@$_POST['content']);
 // 有指定uid则向uid所在socket组发送数据
 if($to){
 $sender_io->to($to)->emit('new_msg', $_POST['content']);
 // 否则向所有uid推送数据
 }else{
 $sender_io->emit('new_msg', @$_POST['content']);
 }
 // http接口返回,如果用户离线socket返回fail
 if($to && !isset($uidConnectionMap[$to])){
 return $http_connection->send('offline');
 }else{
 return $http_connection->send('ok');
 }
 }
 return $http_connection->send('fail');
 };
  
});
  
if(!defined('GLOBAL_START'))
{
 Worker::runAll();
}
相关教程