創(chuàng)建一個(gè)異步服務(wù)器程序,支持TCP、UDP、UnixSocket 3種協(xié)議,支持IPv4和IPv6,支持SSL/TLS單向雙向證書的隧道加密。使用者無需關(guān)注底層實(shí)現(xiàn)細(xì)節(jié),僅需要設(shè)置網(wǎng)絡(luò)事件的回調(diào)函數(shù)即可。
swoole_server只能用于php-cli環(huán)境,否則會(huì)拋出致命錯(cuò)誤
$serv = new swoole_server("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
$serv->set(array(
'worker_num' => 4,
'daemonize' => true,
'backlog' => 128,
));
$serv->on('Connect', 'my_onConnect');
$serv->on('Receive', 'my_onReceive');
$serv->on('Close', 'my_onClose');
PHP中可以使用4種回調(diào)函數(shù)的風(fēng)格
$serv->start();
$serv->manager_pid; //管理進(jìn)程的PID,通過向管理進(jìn)程發(fā)送SIGUSR1信號(hào)可實(shí)現(xiàn)柔性重啟
$serv->master_pid; //主進(jìn)程的PID,通過向主進(jìn)程發(fā)送SIGTERM信號(hào)可安全關(guān)閉服務(wù)器
$serv->connections; //當(dāng)前服務(wù)器的客戶端連接,可使用foreach遍歷所有連接
$serv = new Swoole\Server("127.0.0.1", 9501);
//設(shè)置服務(wù)器參數(shù)
$serv->set(array(
'worker_num' => 8, //工作進(jìn)程數(shù)量
'daemonize' => true, //是否作為守護(hù)進(jìn)程
));
//設(shè)置事件回調(diào)函數(shù)
$serv->on('connect', function ($serv, $fd) {
echo "Client:Connect.\n";
});
$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
$serv->send($fd, 'Swoole: ' . $data);
$serv->close($fd);
});
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});
//啟動(dòng)服務(wù)器
$serv->start();
更多建議: