2012-11-03 wcdj
Web服务器的含义
Web服务器会对HTTP请求进行处理并提供响应。“Web服务器”可以用来表示:
(1) Web服务器的软件;
(2) Web服务器设备,即预先打包好的软硬件解决方案;
Web服务器的实现
Web服务器实现了HTTP和相关的TCP连接处理,负责管理Web服务器提供的资源,以及对Web服务器的配置、控制及扩展方面的管理。
Web服务器处理请求的基本步骤
(1) 建立连接。接受一个客户端连接,或者如果不希望与这个客户端建立连接,就将其关闭;
(2) 接收请求。从网络中读取一条HTTP请求报文;
(3) 处理请求。对请求报文进行解释,并采取行动;
(4) 访问资源。访问报文中指定的资源;
(5) 构建响应。创建带有正确首部的HTTP响应报文;
(6) 发送响应。将响应回送给客户端;
(7) 记录事务处理过程。将与已完成事务有关的内容记录在一个日志文件中;
一个简单的Perl Web服务器
#!/usr/bin/perl
#==============
# Date: 2012-11-03
# User: wcdj
#==============
use Socket;
use Carp;
use FileHandle;
# [1] use port 8080 by default, unless overridden on command line
$port = (@ARGV ? $ARGV[0] : 8080);
# [2] create local TCP socket and set it to listen for connections
$proto = getprotobyname('tcp');
socket(S, PF_INET, SOCK_STREAM, $proto) || die;
setsockopt(S, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) || die;
bind(S, sockaddr_in($port, INADDR_ANY)) || die;
listen(S, SOMAXCONN) || die;
# [3] print a startup message
printf("<<< perl_web_svr accepting on port %d >>>\n\n", $port);
while (1)
{
# [4] wait for a connection C(Client)
$cport_caddr = accept(C, S);
($cport, $caddr) = sockaddr_in($cport_caddr);
C->autoflush(1);
# [5] print who the connection is from
$cname = gethostbyaddr($caddr, AF_INET);
printf("<<< request from [%s] >>>\n", $cname);
# [6] read request msg until blank line, and print on screen
while ($line = <C>)
{
print $line;
if ($line =~ /^\r/) {last; }
}
# [7] prompt for response msg, and input response lines,
# sending response lines to client, until solitary "."
printf("<<< type response followed by '.' >>>\n");
while ($line = <STDIN>)
{
$line =~ s/\r//;
$line =~ s/\n//;
if ($line =~ /^\./) {last; }
print C $line . "\r\n";
}
close(C);
}