Home > Backend Development > PHP Tutorial > Code example of php multi-process processing tcp connection

Code example of php multi-process processing tcp connection

不言
Release: 2023-04-04 13:28:02
forward
2299 people have browsed it

This article brings you code examples about PHP multi-process processing of TCP connections. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The code is as follows:

<?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,&#39;127.0.0.1&#39;, 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);

        //子进程
        if(pcntl_fork() == 0)
        {   
                $recv = socket_read($conn, 8192);
                //处理数据
                $send_data = "server: ".$recv;
                socket_write($conn, $send_data);
                socket_close($conn);
                exit(0);
        }   
        else
        {   
                socket_close($conn);
        }   
}
Copy after login

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

php multi-process explanation

<?php

$pid = pcntl_fork();
//父进程和子进程都会执行下面代码
if ($pid == -1) {
    //错误处理:创建子进程失败时返回-1.
     die(&#39;could not fork&#39;);
} else if ($pid) {
     //父进程会得到子进程号,所以这里是父进程执行的逻辑
     pcntl_wait($status); //等待子进程中断,防止子进程成为僵尸进程。
} else {
     //子进程得到的$pid为0, 所以这里是子进程执行的逻辑。
}
?>
Copy after login

The above is the detailed content of Code example of php multi-process processing tcp connection. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template