仿照workerman写了个最简单的tcp server,但不知道该怎么处理客户端关闭连接时的情况

星际争霸小王子
<?php      
    main();
    function main()
    {      

        $pid=pcntl_fork();
        if($pid)
        {
            exit(0);
        }
        else
        {
            posix_setsid();
            $pid=pcntl_fork();
            if($pid)
            {
                exit(0);
            } 
            cli_set_process_title('mysocket');               
            $stream_rs=stream_socket_server("tcp://127.0.0.1:2345",$errno,$errstr);
            $socket   = socket_import_stream($stream_rs);
            socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
            socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1);
            stream_set_blocking($stream_rs, 0);
            //fork 2 subprocess
            $i=2;
            while($i--)
            {
                $pid=pcntl_fork();   
                if($pid)
                { 
                }
                else
                {                   
                    cli_set_process_title('submysocket');                   
                    $base_event=event_base_new();
                    $event=event_new();  
                    event_set($event, $stream_rs, EV_READ | EV_PERSIST , "acceptConnection", null);
                    event_base_set($event, $base_event);
                    event_add($event);
                    event_base_loop($base_event); 
                }
            }  
            $pid=pcntl_wait($stats); 
            echo $pid."has exit \n";
        }
    }

    function acceptConnection($socket)
    {        
        $new_stream = @stream_socket_accept($socket, 0); 
        if($new_stream===false)
        {
            return;
        }
        echo 'coming..';          
        stream_set_blocking($new_stream, 0);
        $base_event=event_base_new();
        $event=event_new();  
        event_set($event, $new_stream, EV_READ | EV_PERSIST , "baseRead", null);
        event_base_set($event, $base_event);
        event_add($event);
        event_base_loop($base_event);        
    }
    function baseRead($socket)
    {       
        $buf='';
        $buf_length=8192;
        while($str=fread($socket, $buf_length))
        {
            $buf.=$str;
        }
        myecho($buf);

    }
    function myecho($str)
    {
        if (!empty($str))
            echo $str;
    }
?>

以上是所有源代码,我的客户端是telnet 127.0.0.1 2345,但是现在的问题是worker进程不知道客户端退出了,还在傻傻地等,所以想请教群主怎么修改这段代码

6687 3 0
3个回答

walkor 打赏
function baseRead($socket)
{
    if(feof($socket))
    {
        ..............
    }
    $buf='';
    $buf_length=8192;
    while($str=fread($socket, $buf_length))
    {
        $buf.=$str;
    }
    myecho($buf);
}
  • 暂无评论

谢谢boss

  • 暂无评论

我还有问题!
1. 我觉得我这个代码在event上有问题。现在的情况是,我只开了一个worker ,一旦telnet连接上服务器了,再开一个telnet的话,新开的就不会到acceptConnection函数里面去.
2.

if(feof($socket))
{
    unset($socket);         
    return;
}

这样写有什么问题吗?

还请多多指教!

  • 暂无评论
年代过于久远,无法发表回答
×
🔝