PHP multiprocess processing tcp connection

<?php
if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0)
{
        echo "failed to create socket: ".socket_strerror($sock)."n";
        exit();
}

if(($ret = socket_bind($sock,'127.0.0.1', 8888)) < 0)
{
        echo "failed to bind socket: ".socket_strerror($ret)."n";
        exit();
}

if( ( $ret = socket_listen( $sock, 0 ) ) < 0 ) 
{
        echo "failed to listen to socket: ".socket_strerror($ret)."n";
        exit();
}

while (true)
{
        $conn = @socket_accept($sock);

        //Subprocess
        if(pcntl_fork() == 0)
        {   
                $recv = socket_read($conn, 8192);
                //Processing data
                $send_data = "server: ".$recv;
                socket_write($conn, $send_data);
                socket_close($conn);
                exit(0);
        }   
        else
        {   
                socket_close($conn);
        }   
}

Each connection corresponds to a process, similar to apache's work mode

An overview of php multiprocessing

<?php

$pid = pcntl_fork();
//Both the parent and child processes execute the following code
if ($pid == -1) {
    //Error handling: Return - 1 when failed to create child process
     die('could not fork');
} else if ($pid) {
     //The parent process will get the child process number, so here is the logic of the parent process execution
     pcntl_wait($status); //Wait for the subprocess to be interrupted to prevent the subprocess from becoming a zombie process.
} else {
     //The sub process gets $pid of 0, so here is the logic of the sub process execution.
}
?>

I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced. There is no sense of direction when they write too much business code. I don't know where to start to improve. For this, I collated some data, including but not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, SW For advanced advanced dry goods of many knowledge points, such as oole, Swoft, Kafka, Mysql optimization, shell script, Docker, microservice, Nginx, etc., you can share what you need for free. You need to stamp here PHP advanced architect > > > free access to video and interview documents

Tags: Programming PHP socket Apache Laravel

Posted on Thu, 28 May 2020 10:07:18 -0400 by jay7981