当你的服务器需要一个简单的接口,你会考虑利用这个接口构造一个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脚本中是简单的。