文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>使用select

使用select

时间:2007-06-13  来源:transfan

Using select()
最近用Perl写的程序都是使用socket读写,并发访问时直接使用fork。这样做可以缩短响应时间,但耗费大量系统资源,需要有可靠手段对子进程进行管理,控制访问连接数量,提高每路进程的利用率。
select方法可在同一个进程中处理多个IO(每次取出加进去的IO集合里面已就绪的子集),在网上搜出下面一段代码,很好地演示了select的用法(针对IO::Select对象)。

... create socket as before ...
use IO::Select;
$read_set = new IO::Select(); # create handle set for reading

$read_set->add($s); # add the main socket to the set


while (1) { # forever

    # get a set of readable handles (blocks until at least one handle is ready)

    my ($rh_set) = IO::Select->select($read_set, undef, undef, 0);
    # take all readable handles in turn

    foreach $rh (@$rh_set) {
    # if it is the main socket then we have an incoming connection and

    # we should accept() it and then add the new socket to the $read_set

        if ($rh == $s) {
            $ns = $rh->accept();
            $read_set->add($ns);
        }
        # otherwise it is an ordinary socket and we should read and process the request

        else {
            $buf = <$rh>;
            if($buf) { # we get normal input
   
            # ... process $buf ...

            }
            else { # the client has closed the socket

                # remove the socket from the $read_set and close it

                $read_set->remove($rh);
                close($rh);
            }
        }
    }
}

相关阅读 更多 +
排行榜 更多 +
枪战特训2

枪战特训2

飞行射击 下载
打击者19452代最新版

打击者19452代最新版

飞行射击 下载
方块枪战战场安卓版

方块枪战战场安卓版

飞行射击 下载