use Socket;
use Carp;
use FileHandle;
# 默认使用8080端口,除非人工指定
$port = (@AEGV ? $ARGV[0] : 8080);
#创建本地TCP端口用于侦听连接
$proto = getprotobyname('tcp');
eval{
socket(S,PF_INET,SOCK_STREAM,$proto) || die;
};
print @?;
setsockopt(S,SOL_SOCKET,SO_REUSEADDR,1);
bind(S,sockaddr_in($port,INADDR_ANY)) || die;
listen(S,SOMAXCONN) || die;
#打印一个启动消息
printf(" <<<Type-o-Serve Accepting on port %d>>>
",$port);
while (1)
{
#等待一个连接C
$cport_caddr = accept(C,S);
($cport,$caddr) = sockaddr_in($cport_caddr);
C->autoflush(1);
#打印出从哪里来的连接
$cname = gethostbyaddr($caddr,AF_INET);
printf(" <<<Request From '%s' >>>
",$cname);
#读取请求直到空行,打印到屏幕
while ($line =<C>)
{
print $line;
if ($line =~ /^
/){last;}
}
##提示响应消息,输入响应行
##发送响应行到客户端,直到单独的.
printf (" <<<Type Response Followed by '.' >>>
");
while ($line =<STDIN>)
{
$line =~ s/
//;
$line =~ s/
//;
if ($line =~ /^./) {last;}
print C $line."
";
}
}