1分钟部署网站📞AI智能客服,大模型训练自有数据,简单好用,有效降低客服成本 广告
# Server::\_\_construct [TOC] 创建一个异步`Server`对象。 ~~~ $serv = new 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`监听全部地址 * IPv4使用`127.0.0.1`表示监听本机,`0.0.0.0`表示监听所有地址 * IPv6使用`::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](ssl\_cert\_file.md) * `1.7.11`版本增加了对`Unix Socket`的支持,详细请参见[/wiki/page/16.html](Server-addListener.md) * 构造函数中的参数与`swoole_server::addlistener`中是完全相同的 * **高负载的服务器,请务必调整[Linux内核参数](内核参数调整.md)** * [2种Server运行模式介绍](Server的两种运行模式介绍.md) ## 异常 监听端口失败会抛出异常,可以使用`try/catch`捕获异常 ## 注意事项 * 底层有保护机制,一个`PHP`程序内只能创建启动一个`Server`实例 * 如果要实现多个`Server`实例的管理,父进程必须使用`exec`,不得使用`fork` ## 随机可用端口 `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(); ~~~ ## SYSTEMD监听端口 `1.9.7`增加了对`systemd socket`的支持。监听端口由`systemd`配置指定。 #### swoole.socket ~~~ [Unit] Description=Swoole Socket [Socket] ListenStream=9501 Accept=false [Install] WantedBy = sockets.target ~~~ #### swoole.service ~~~ [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 ~~~ #### server.php ~~~ $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 ~~~