ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# swoole_server::__construct 创建一个异步`Server`对象。 ```php $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`监听全部地址 * 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](https://wiki.swoole.com/wiki/page/318.html) * `1.7.11`版本增加了对`Unix Socket`的支持,详细请参见 [/wiki/page/16.html](https://wiki.swoole.com/wiki/page/16.html) * 构造函数中的参数与`swoole_server::addlistener`中是完全相同的 * 监听端口失败,在`1.9.16`以上版本会抛出异常,可以使用`try/catch`捕获异常,在`1.9.16`以下版本抛出致命错误 * __高负载的服务器,请务必调整[Linux内核参数](https://wiki.swoole.com/wiki/page/11)__ * [ 2种Server运行模式介绍](https://wiki.swoole.com/wiki/page/353.html) 注意事项 ---- * 底层有保护机制,一个`PHP`程序内只能创建启动一个`Server`实例 * 如果要实现多个`Server`实例的管理,父进程必须使用`exec`,不得使用`fork` 随机可用端口 ---- swoole-1.9.6增加了随机监听可用端口的支持,`$port`参数可以设置为0,操作系统会随机分配一个可用的端口,进行监听。可以通过读取`$server->port`得到分配到的端口号。 ```php $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监听端口 ---- swoole-1.9.7增加了对`systemd socket`的支持。监听端口由`systemd`配置指定。 #### swoole.socket ```shell [Unit] Description=Swoole Socket [Socket] ListenStream=9501 Accept=false [Install] WantedBy = sockets.target ``` #### swoole.service ```shell [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 ```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(); ``` #### 启动服务 ```shell sudo systemctl enable swoole.socket sudo systemctl start swoole.socket sudo systemctl start swoole.service ```