SoFunction
Updated on 2025-03-10

Complete example of a simple multi-process server class implemented by php

This article describes the simple multi-process server class implemented by PHP. Share it for your reference, as follows:

A simple multi-process server written by php.

<?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 parameters');
    }
    //As long as we receive the client's data, we will fork a child process    while ($client = socket_accept($this->server)) { //Waiting for the client to access, the return is the client's connection      $buf = socket_read($client, 1024); //Read client content      $pid=pcntl_fork(); //Create child process      //The parent and child processes will execute the following code      if ($pid == -1) {
        //Error handling: Return -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 for the parent process to execute        var_dump('Parent Process',$pid);
        pcntl_wait($status); //Waiting for the child process to interrupt to prevent the child process from becoming a zombie process.      } else {
        //The $pid obtained by the child process is 0, so here is the logic for the child process to execute.        //Sleep        if($this->checkRule("/sleep/i",$buf)){
          sleep(10);
          $this->response('Dormant 10S',$client);
          socket_close($client);
          return;
        }
        //Request filtering        if(empty($this->checkRule("/GET\s(.*?)\sHTTP\/1.1/i",$buf))){
          socket_close($client);
          return;
        }
        //response        $response= call_user_func($callback,$buf); //Calling back $callback function        $this->response($response,$client);
        usleep(1000); //Subtle is unit, 10000000 subtle is equal to 1 second        socket_close($client);
        exit(); //Exit directly      }
    }
//    while (true) {
//      $client = socket_accept($this->server); //Waiting for the client to access, the return is the client's connection//      $buf = socket_read($client, 1024); //Read client content//
//      //Sleep//      if($this->checkRule("/sleep/i",$buf)){
//        sleep(10);
// $this->response('Sleep 10S',$client);//        socket_close($client);
//        return;
//      }
//      //Request filtering//      if(empty($this->checkRule("/GET\s(.*?)\sHTTP\/1.1/i",$buf))){
//        socket_close($client);
//        return;
//      }
//
//      //response//      $response= call_user_func($callback,$buf); //Calling back $callback function//      $this->response($response,$client);
//      usleep(1000); //Subtle is unit, 10000000 subtle is equal to 1 second//      socket_close($client);
//
//    }
    socket_close($this->server);
  }
  //io reuse  //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); //The reuse is still in TIME_WAIT    socket_bind($this->server, $this->ip, $this->port); //The detailed processing is done by yourself    socket_listen($this->server); //Start monitoring  }
  /**
    * 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 allow access to http protocol// if(preg_match("GET\s(.*?)\sHTTP/1.1",$buf,$matchs)){ //Match to http protocol//      return true;
//    }else{
//      return false;
//    }
    //2. Filter out/    //3. Obtain request information  }
  protected function response($content,$client){
    //Return data to the client, respond to 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);
  }
}

For more information about PHP related content, please check out the topic of 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 (Array) operation techniques》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.