接收 HTTP POST 请求,如何在 Perl 中获取空行后面的行?
我的程序似乎在检测到空行后停止,直到我按下浏览器中的停止按钮。
按下停止按钮之前:
按下停止按钮之后:
这是代码的一部分:
while (accept CONNECTION, SERVER ) {
select CONNECTION; $| = 1; select STDOUT;
print "\n>> Client connected at ", scalar(localtime), "\n";
my $isGet = 1;
my $isPostAndBlankLineDetected = 0;
while (<CONNECTION>) {
s/\r?\n//;
my $msg = $_;
rubyP "$msg";
if ($msg =~ /GET/) {
processGet($msg);
last;
}
if ($msg =~ /POST/) {
setReqMethodAndReturnUri($msg);
$isGet = 0;
}
if ($isPostAndBlankLineDetected) {
pp "isPostAndBlankLineDetected is true";
last;
}
if( ! $isGet) { #isPost
if ($msg =~ /Content-Length/) {
setContentLength($msg);
}
if ($msg eq "") {
$isPostAndBlankLineDetected = 1;
pp "done setting isPostAndBlankLineDetected";
}
}
}
close CONNECTION;
print ">> Client disconnected\n";
}
我在 if ($isPostAndBlankLineDetected)last
语句代码>.
这是套接字部分:
use Socket;
require "helper.pl";
sub rubyP { #print raw string
my $arg = $_;
use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper $arg;
}
sub pp {
print "DEBUG: '$_[0]'\n";
}
my $protocol = getprotobyname 'tcp';
my $port = 15032;
my $server_addr = sockaddr_in($port, INADDR_ANY);
socket SERVER, AF_INET, SOCK_STREAM, $protocol
or die "Unable to create socket: $!";
bind SERVER, $server_addr
or die "Unable to bind: $!";
listen SERVER, SOMAXCONN;
My program seems stopped after the blank line detected until I press the stop button in broswer.
Before the stop button is pressed:
After the stop button is pressed:
Here is part of the code:
while (accept CONNECTION, SERVER ) {
select CONNECTION; $| = 1; select STDOUT;
print "\n>> Client connected at ", scalar(localtime), "\n";
my $isGet = 1;
my $isPostAndBlankLineDetected = 0;
while (<CONNECTION>) {
s/\r?\n//;
my $msg = $_;
rubyP "$msg";
if ($msg =~ /GET/) {
processGet($msg);
last;
}
if ($msg =~ /POST/) {
setReqMethodAndReturnUri($msg);
$isGet = 0;
}
if ($isPostAndBlankLineDetected) {
pp "isPostAndBlankLineDetected is true";
last;
}
if( ! $isGet) { #isPost
if ($msg =~ /Content-Length/) {
setContentLength($msg);
}
if ($msg eq "") {
$isPostAndBlankLineDetected = 1;
pp "done setting isPostAndBlankLineDetected";
}
}
}
close CONNECTION;
print ">> Client disconnected\n";
}
I have a last
statement in if ($isPostAndBlankLineDetected)
.
Here is the socket part:
use Socket;
require "helper.pl";
sub rubyP { #print raw string
my $arg = $_;
use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper $arg;
}
sub pp {
print "DEBUG: '$_[0]'\n";
}
my $protocol = getprotobyname 'tcp';
my $port = 15032;
my $server_addr = sockaddr_in($port, INADDR_ANY);
socket SERVER, AF_INET, SOCK_STREAM, $protocol
or die "Unable to create socket: $!";
bind SERVER, $server_addr
or die "Unable to bind: $!";
listen SERVER, SOMAXCONN;
您错误地认为后面有一条“线”。即使发生了一些事情,它也可能不会以换行符结束。
读取
Content-Length
字节。You falsely assume there is a "line" that follows. Even if something follows, it might not be ended by have a newline.
read
Content-Length
bytes.