利用HTTP::Daemon模块构件简单的Web服务器

ZDNet软件频道 时间:2004-01-29 作者:ZDNet China |  我要评论()
本文关键词:perl
当你的服务器需要一个简单的接口,你会考虑利用这个接口构造一个Web服务器到你的应用程序中。在Perl中使用HTTP::Daemon模版构造一个基本的Web服务器是非常简单的。
本文译自TechRepublic,未经许可请勿转载

    当你的服务器需要一个简单的接口,你会考虑利用这个接口构造一个Web服务器到你的应用程序中。在perl中使用HTTP::Daemon模版构造一个基本的Web服务器是非常简单的。这个模版将完成大量和获得请求和发送回复的工作。

下面的代码是完整的Web服务器。它发送了一个请求类型的响应指示,被请求路径,请求头文件和当前时间:

use HTTP::Daemon;
use HTTP::Status;
use HTTP::Response;

my $daemon = new HTTP::Daemon LocalAddr => 'localhost', LocalPort => 1234;

print "Server open at ", $daemon->url, " ";

while (my $connection = $daemon->accept)
{
    print Identify($connection) . " Connected ";
    while (my $request = $connection->get_request)
    {
        print Identify($connection) . " Requested $ $ ";
        if ($request->method eq 'GET')
        {
            $response = HTTP::Response->new(200);
            $response->content(<<EOT);
<html>
<head><title>Simple Web server</title></head>
<body>
<p>You requested path <b><i>$</b></i>
using protocol <b><i>$</b></i>
via method <b><i>$</b></i>
<p>Your header information was:<br>
${join '<br>', split(/ /, $request->headers_as_string())}

<p>I'm a simple server so that's all you are going to get!
<p>Generated ${scalar localtime}
</body>
</html>
EOT
            $connection->force_last_request; # allows us to service multiple clients
            $connection->send_response($response);
        }
        else
        {
            $connection->send_error(RC_FORBIDDEN)
        }
    }
    print "$:$ Closed ";
    $connection->close;
    undef($connection);
}

sub Identify
{
    my ($conn) = @_;

    return "$:$";
}

在循环的时候通过简单的替换最里层的代码,你可以让你的Web服务器完成任何你想要完成的事情。比如,你可以返回你程序的位置或者从Web照相机中获得一个图片。

当你使用HTTP::Daemon模版的时候添加一个Web接口到你的perl脚本中是简单的。



责任编辑:李宁

欢迎评论投稿

百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134