创建一个异步Server
对象。
$serv = new swoole_server(string $host, int $port = 0, int $mode = SWOOLE_PROCESS,
int $sock_type = SWOOLE_SOCK_TCP);
$host
参数用来指定监听的ip地址,如127.0.0.1
,或者外网地址,或者0.0.0.0
监听全部地址
127.0.0.1
表示监听本机,0.0.0.0
表示监听所有地址::1
表示监听本机,::
(相当于0:0:0:0:0:0:0:0
) 表示监听所有地址$port
监听的端口,如9501
$sock_type
为UnixSocket Stream/Dgram
,此参数将被忽略1024
端口需要root
权限server->start
时会失败$mode
运行的模式
SWOOLE_PROCESS
多进程模式(默认)SWOOLE_BASE
基本模式$sock_type
指定Socket
的类型,支持TCP
、UDP
、TCP6
、UDP6
、UnixSocket Stream/Dgram
6种$sock_type | SWOOLE_SSL
可以启用SSL
隧道加密。启用SSL
后必须配置ssl_key_file和ssl_cert_file
1.7.11
版本增加了对Unix Socket
的支持,详细请参见 /wiki/page/16.html
swoole_server::addlistener
中是完全相同的1.9.16
以上版本会抛出异常,可以使用try/catch
捕获异常,在1.9.16
以下版本抛出致命错误PHP
程序内只能创建启动一个Server
实例Server
实例的管理,父进程必须使用exec
,不得使用fork
swoole-1.9.6增加了随机监听可用端口的支持,$port
参数可以设置为0,操作系统会随机分配一个可用的端口,进行监听。可以通过读取$server->port
得到分配到的端口号。
$http = new swoole_http_server("0.0.0.0");
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
swoole-1.9.7增加了对systemd socket
的支持。监听端口由systemd
配置指定。
[Unit]
Description=Swoole Socket
[Socket]
ListenStream=9501
Accept=false
[Install]
WantedBy = sockets.target
[Service]
Type=forking
PIDFile=/var/run/swoole.pid
ExecStart=/usr/bin/php /var/www/swoole/server.php
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -USR1 $MAINPID
[Install]
WantedBy = multi-user.target
$http = new swoole_http_server("systemd");
$http->set([
'daemonize' => true,
'pid_file' => '/var/run/swoole.pid',
]);
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
sudo systemctl enable swoole.socket
sudo systemctl start swoole.socket
sudo systemctl start swoole.service