HTTP Server小测试程序

一个能够兼容所有特性的HTTP服务器是十分复杂的,特别是一些可选项,或者是一些非传统非标准的字段的处理,更是超级麻烦

下面这个小的web server程序,不仅仅是类socket服务端接收程序,还可以返回给客户端,可以当一个测试程序,测试客户端和代理交互情况;当然如果你手快用C语言来写Socket交互,那么请直接跳过就行了

#!/usr/bin/perl -w

use Socket;
use Carp;
use FileHandle;

#use port 8080 by default ,unless overridden on command line
$port = (@ARGV ? $ARGV[0] : 8080);

#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, 1) || die;
bind(S, sockaddr_in($port, INADDR_ANY)) || die;
listen(S, SOMAXCONN) || die;

#print a startup message
printf("HTTP Server Accepting on Port %d:\n\n", $port);

while(1){
    #wait for a connection C
    $cport_caddr = accept(C, S);
    ($cport, $caddr) = sockaddr_in($cport_caddr);
    C->autoflush(1);

    #print who the connection is from
    $cname = gethostbyaddr($caddr, AF_INET);
    printf("Request From: '%s'\n", $cname);

    #read request msg until blank line, and print on screen
    while ($line = <C>){
        print $line;
        if ($line =~ /^\r/) { last; };
    }

    #prompt for response message, 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);
}

可以看到中间也是通过socket服务端来接收数据,socket,bind,listen,accept等;这里直接用一个python脚本来通过socket模拟client向9999端口发送一些http信息

服务端
[lihui@localhost ~]# ./web.pl 9999
HTTP Server Accepting on Port 9999:

Request From: ''
GET / HTTP/1.1
Host: lihuia.com 
Connection:keep-alive
Cache-Control:max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4

Type Response Followed by '.'

客户端
[lihui@localhost ~]# ./client.py 

发表回复