背景:
使用swoole_server swoole_table实现
//创建swoole_table
$table = new swoole_table(1024);
$table->column(‘fd‘, swoole_table::TYPE_INT);
$table->column(‘from_id‘, swoole_table::TYPE_INT);
$table->column(‘data‘, swoole_table::TYPE_STRING, 64);
$table->create();
//创建$sev对象,监听9501端口
$serv = new swoole_server(‘0.0.0.0‘, 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
//设置相关属性
$serv->set(array(
‘ractor_num‘ => 1, //主进程中线程数量
‘worker_num‘ => 2, //工作进程数量
‘daemonize‘ => 0, //是否守护进程
‘log_file‘ => ‘/data/wwwroot/swoole.log‘, //日志存储路径
‘dispatch_mode‘ => 2, //1平均分配,2按FD取摸固定分配,3抢占式分配,默认为取模(dispatch=2)‘
‘task_worker_num‘=> 2,
));
//连接
$serv->on(‘connect‘, function($serv, $fd){
global $table;
$fdinfo = $serv->connection_info($fd);
if (!$table->exist($fd)) {
$table->set($fd,array(‘fd‘=>$fd,‘from_id‘=>$fdinfo[‘from_id‘],‘data‘=>$fdinfo[‘socket_type‘]));
}
});
//接收数据
$serv->on(‘receive‘, function($serv, $fd, $from_id, $data){
if (trim($data)=="sendBroadcast") {
$task_id = $serv->task(‘broadcast‘);
} else {
$serv->send($fd, "hello " . $fd . "i am main process " . $serv->master_pid . " and manger id " . $serv->manager_pid);
}
});
//关闭
$serv->on(‘close‘, function($serv, $fd){
echo $fd . " bye bye!!!";
});
//workstart事件
$serv->on(‘workerstart‘, function($serv, $work_id){
global $argv;
if($work_id >= $serv->setting[‘worker_num‘]){
swoole_set_process_name("php {$argv[0]} task worker");
}else{
swoole_set_process_name("php {$argv[0]} work worker");
}
});
//server task
$serv->on(‘task‘,function($serv, $taskid, $from_id, $data){
global $table;
foreach($table as $row){
$serv->send($row[‘fd‘],"{$row[‘fd‘]} i am broadcast");
}
$serv->finish("$data -> OK");
});
//处理异步任务的结果
$serv->on(‘finish‘, function ($serv, $task_id, $data) {
echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});
//启动
$serv->start();