Background:
Implemented with Swoole_server swoole_table
Create 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 ();
Create a $sev object and listen on port 9501
$serv = new Swoole_server (' 0.0.0.0 ', 9501, swoole_process, swoole_sock_tcp);
Setting related properties
$serv->set (Array (
' Ractor_num ' = 1,//number of threads in the main process
' Worker_num ' = 2,//number of work processes
' daemonize ' = + 0,//whether daemon
' Log_file ' = '/data/wwwroot/swoole.log ',//log storage path
' Dispatch_mode ' + 2,//1 average distribution, 2 per FD to get a fixed allocation, 3 preemptive allocation, default to modulo (dispatch=2) '
' Task_worker_num ' = 2,
));
Connection
$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 ']);
}
});
Receive data
$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);
}
});
Shut down
$serv->on (' Close ', function ($serv, $FD) {
Echo $FD. "Bye bye!!!";
});
Workstart Events
$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");
});
Handling the results of an asynchronous task
$serv->on (' Finish ', function ($serv, $task _id, $data) {
echo "asynctask[$task _id] Finish: $data". Php_eol;
});
Start
$serv->start ();
Swoole Broadcast Message implementation