Skip to content

Commit

Permalink
support SO_REUSEPORT for php7
Browse files Browse the repository at this point in the history
  • Loading branch information
walkor committed Oct 22, 2015
1 parent e119df8 commit a67f62b
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class Worker
* 版本号
* @var string
*/
const VERSION = '3.2.1';
const VERSION = '3.2.2';

/**
* 状态 启动中
Expand Down Expand Up @@ -108,6 +108,12 @@ class Worker
* @var bool
*/
public $reloadable = true;

/**
* reuse port
* @var bool
*/
public $reusePort = false;

/**
* 当worker进程启动时,如果设置了$onWorkerStart回调函数,则运行
Expand Down Expand Up @@ -416,8 +422,12 @@ protected static function initWorkers()
{
self::$_maxUserNameLength = $user_name_length;
}
// 监听端口
$worker->listen();
// 如果端口不可复用,则直接在主进程就监听
if(!$worker->reusePort)
{
// 监听端口
$worker->listen();
}
}
}

Expand Down Expand Up @@ -800,6 +810,11 @@ protected static function forkOneWorker($worker)
// 子进程运行
elseif(0 === $pid)
{
// 如果设置了端口复用,则在子进程执行监听
if($worker->reusePort)
{
$worker->listen();
}
// 启动过程中尝试重定向标准输出
if(self::$_status === self::STATUS_STARTING)
{
Expand Down Expand Up @@ -1228,13 +1243,14 @@ public function __construct($socket_name = '', $context_option = array())
*/
public function listen()
{
// 设置自动加载根目录
Autoloader::setRootPath($this->_appInitPath);

if(!$this->_socketName)
if(!$this->_socketName || $this->_mainSocket)
{
return;
}

// 设置自动加载根目录
Autoloader::setRootPath($this->_appInitPath);

// 获得应用层通讯协议以及监听的地址
list($scheme, $address) = explode(':', $this->_socketName, 2);
// 如果有指定应用层协议,则检查对应的协议类是否存在
Expand All @@ -1260,6 +1276,11 @@ public function listen()
$flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
$errno = 0;
$errmsg = '';
// 如果设置了端口复用,则设置SO_REUSEPORT选项为1
if($this->reusePort)
{
stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
}
$this->_mainSocket = stream_socket_server($this->transport.":".$address, $errno, $errmsg, $flags, $this->_context);
if(!$this->_mainSocket)
{
Expand Down

0 comments on commit a67f62b

Please sign in to comment.