Complete example of a simple multi process server class implemented in PHP

Time:2021-8-11

This article describes a simple multi process server class implemented in PHP. Share with you for your reference, as follows:

PHP to write a simple multi process server.

<?php
class server
{
  public $port;
  public $ip;
  protected $server;
  public function __construct($ip = '0.0.0.0', $port)
  {
    $this->ip = $ip;
    $this->port = $port;
    $this->createSocket(); // Create a communication node
  }
  public function listen($callback)
  {
    if(!is_callable($callback)){
      Throw new exception ('not a closure, please pass the correct parameter ');
    }
    //As long as we receive the data from the client, we fork a sub process to process it
    while ($client = socket_ Accept ($this - > server)) {// wait for the client to access. The client's connection is returned
      $buf = socket_ read($client, 1024); // Read client content
      $pid=pcntl_ fork(); // Create child process
      //Both parent and child processes execute the following code
      if ($pid == -1) {
        //Error handling: returns - 1 when creating a child process fails
        die('could not fork');
      } else if ($pid) {
        //The parent process will get the child process number, so here is the logic executed by the parent process
        var_ Dump ('parent process', $PID);
        pcntl_ wait($status); // Wait for the subprocess to interrupt to prevent the subprocess from becoming a zombie process.
      } else {
        //The $PID obtained by the child process is 0, so here is the logic executed by the child process.
        //Sleep
        if($this->checkRule("/sleep/i",$buf)){
          sleep(10);
          $this - > response ('sleep for 10s', $client);
          socket_close($client);
          return;
        }
        //Request filtering
        if(empty($this->checkRule("/GET\s(.*?)\sHTTP\/1.1/i",$buf))){
          socket_close($client);
          return;
        }
        //Respond
        $response= call_ user_ func($callback,$buf); // Callback $callback function
        $this->response($response,$client);
        usleep(1000); // In subtlety, 1000000 subtlety is equal to 1 second
        socket_close($client);
        exit(); // immediate withdrawal
      }
    }
//    while (true) {
//      $client = socket_ accept($this->server); // Wait for the client to access and return the connection of the client
//      $buf = socket_ read($client, 1024); // Read client content
//
//      //Sleep
//      if($this->checkRule("/sleep/i",$buf)){
//        sleep(10);
//        $this - > response ('sleep for 10s', $client);
//        socket_close($client);
//        return;
//      }
//      //Request filtering
//      if(empty($this->checkRule("/GET\s(.*?)\sHTTP\/1.1/i",$buf))){
//        socket_close($client);
//        return;
//      }
//
//      //Respond
//      $response= call_ user_ func($callback,$buf); // Callback $callback function
//      $this->response($response,$client);
//      usleep(1000); // In subtlety, 1000000 subtlety is equal to 1 second
//      socket_close($client);
//
//    }
    socket_close($this->server);
  }
  //IO multiplexing
  //Epoll model
  //Multi process
  protected function createSocket()
  {
    $this->server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    //bind
    socket_ set_ option($this->server, SOL_ SOCKET, SO_ REUSEADDR, 1); // Reuse is still in time_ WAIT
    socket_ bind($this->server, $this->ip, $this->port); // The detailed processing shall be completed by itself
    socket_ listen($this->server); // Start listening
  }
  /**
   *Protocol filtering
   * @param $reg
   * @param $buf
   * @return mixed
   */
  protected function checkRule($reg,$buf){
    if(preg_match($reg,$buf,$matchs)){
      return $matchs;
    }
    return false;
  }
  //Request processing class
  public function request($buf){
    //1. Only HTTP protocol access is allowed
//    if(preg_ match("GET\s(.*?)\ SHTTP / 1.1 ", $buf, $matches)) {// matches the HTTP protocol
//      return true;
//    }else{
//      return false;
//    }
    //2. Filter out / favicon.ico
    //3. Obtain request information
  }
  protected function response($content,$client){
    //Return data to the client for response processing
    $string="HTTP/1.1 200 OK\r\n";
    $string.="Content-Type: text/html;charset=utf-8\r\n";
    $string.="Content-Length: ".strlen($content)."\r\n\r\n";
    socket_write($client,$string.$content);
  }
}

Readers interested in more PHP related content can check the topics on this site: summary of PHP process and thread operation skills, summary of PHP network programming skills, introduction to PHP basic syntax, complete collection of PHP array operation skills, summary of PHP string usage Introduction to PHP + MySQL database operation and summary of common PHP database operation skills

I hope this article will help you in PHP programming.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]