I want to create a php server. I made a command to start the server asynchronously. I would like to place an order to stop the server. I can not get the process after running the start command.
Run Command
$server = new Server();
$pid = pcntl_fork();
if ($pid > 0) {
echo "Server Runned";
return;
}
$server->Run();
Server Class
class Server {
private $_loop;
private $_socket;
public function __construct() {
$this->_loop = Factory::create();
$this->_socket = new ReactServer($this->_loop );
$this->_socket->on(
'connection',function ($conn) {
echo "Connection";
}
);
}
public static function Stop () {
$this->_loop-> stop();
}
public function Run () {
$this->_loop->run();
}
}
Thanks for your help !
I have solved my problems.
When i launch my server, i create a file in the tmp directory of system. In my loop, i tcheck if this file is already present. If it was removed, i stop my loop.
So, to stop my server, i can just remove the file.
To can open different server, i name this with host and ports (for exemple : ~/127-0-0-1-8080.pid).
class Loop
{
private $lockFile;
public static function getLockFile($address)
{
return sys_get_temp_dir().'/'.strtr($address, '.:', '--').'.pid';
}
public function __construct($address)
{
$this->lockFile = Loop::getLockFile($address);
touch($this->lockFile);
//...
}
public function run()
{
$this->running = true;
while ($this->running) {
if (!file_exists($this->lockFile)) {
$this->running = false;
echo "File Removed";
}
//...
}
}
public function stop()
{
$this->running = false;
unlink($this->lockFile);
}
}
Start Command :
$server = new Server($em, $port, $host);
$pid = pcntl_fork();
if ($pid > 0) {
$address = $host.":".$port;
echo "Server Starting " . $adresse;
}
$server->Run();
Stop Command :
$host = '127.0.0.1';
$port = 5821;
$lockFile = Loop::getLockFile($host.":".$port);
unlink($lockFile);
echo "Server Stopped";