Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
simple http server that send chunk respomse
use IO::Socket::INET;
$| = 1;
#response头部
my $response_hdr = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nServer: perl tcp server\r\nTransfer-Encoding: chunked\r\nConnection: Keep-Alive\r\n\r\n";
#创建socket,并且监听8888端口
$socket = new IO::Socket::INET (
LocalHost => '0.0.0.0',
LocalPort => '8888',
Proto => 'tcp',
Listen => 5,
Reuse => 1
) or die "ERROR in Socket Creation : $!\n";
while(1)
{
#循环等待client发完请求
$client_socket = $socket->accept();
$request = "";
while(defined($bf = <$client_socket>)) {
$request.=$bf;
#两个\r\n代表请求头发完,详细请阅读rfc2616
if ($request =~ /\r\n\r\n/ and $request =~ /GET/) {
print "we got request \"$request\"\n";
last;
}
}
#开始返回response给client
print $client_socket "$response_hdr"; #打印头
for(my $i = 0;$i < 5;$i ++){ #打印5个数据块,每个数据块长度是6,数据块内容为"1</br>"
print $client_socket "6\r\n1</br>\r\n";
}
print $client_socket "0\r\n\r\n"; #打印最后的一个数据块
# notify client that response has been sent
shutdown($client_socket, 1);
}
$socket->close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment