added httpd.pl, sample http server
This commit is contained in:
93
httpd.pl
Executable file
93
httpd.pl
Executable file
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/perl
|
||||
|
||||
use strict;
|
||||
use warnings "all";
|
||||
use Fcntl;
|
||||
use IO::Socket::INET;
|
||||
|
||||
sub parser($);
|
||||
sub trim($);
|
||||
# auto-flush on socket
|
||||
$| = 1;
|
||||
|
||||
# creating a listening socket
|
||||
my $socket = new IO::Socket::INET (
|
||||
LocalHost => '127.0.0.1',
|
||||
LocalPort => '1488',
|
||||
Proto => 'tcp',
|
||||
Listen => 5,
|
||||
Reuse => 1
|
||||
);
|
||||
|
||||
die "cannot create socket $!\n" unless $socket;
|
||||
print "server waiting for client connection on port 7777\n";
|
||||
|
||||
while(1)
|
||||
{
|
||||
# waiting for a new client connection
|
||||
my $client_socket = $socket->accept();
|
||||
|
||||
# get information about a newly connected client
|
||||
my $client_address = $client_socket->peerhost();
|
||||
my $client_port = $client_socket->peerport();
|
||||
print "connection from $client_address:$client_port\n";
|
||||
|
||||
# read up to 4096 characters from the connected client
|
||||
my $data = "";
|
||||
|
||||
$client_socket->recv($data, 4096);
|
||||
|
||||
print "received data: $data\n";
|
||||
|
||||
my $str = parser($data);
|
||||
# write response data to the connected client
|
||||
$data = "HTTP/1.1 200 OK\n";
|
||||
$data .= "Content-Type: text/plain\n";
|
||||
$data .= "Connection: close\n\n";
|
||||
$data .= $str;
|
||||
|
||||
$client_socket->send($data);
|
||||
|
||||
# notify client that response has been sent
|
||||
shutdown($client_socket, 1);
|
||||
}
|
||||
|
||||
$socket->close();
|
||||
|
||||
sub parser($) {
|
||||
my $data = shift;
|
||||
# return undef if (($data !~ /\r\n\r\n$/) or ($data !~ /\n\n$/));
|
||||
my @headers = (split/\n/, $data);
|
||||
my $hostname = '';
|
||||
my $param = '';
|
||||
my $mesg = 'You requested ';
|
||||
|
||||
foreach (@headers) {
|
||||
my($key, $value) = split(/:\s+/, trim($_));
|
||||
next unless(defined($key));
|
||||
|
||||
if ($key =~ /^HOSTNAME$/i) {
|
||||
$hostname = $value;
|
||||
}
|
||||
|
||||
if ($key =~ /^RTT$/) {
|
||||
$param = $value;
|
||||
}
|
||||
|
||||
if ($key =~ /^LOSS$/) {
|
||||
$param = $value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return "$mesg $hostname $param\n";
|
||||
}
|
||||
|
||||
sub trim ($) {
|
||||
my $param = shift;
|
||||
if ($param =~ /^(\n|\r)/) {$param = substr($param, 1); }
|
||||
if ($param =~ /^(\n|\r)/) {$param = substr($param, 1); }
|
||||
if ($param =~ /(\n|\r)$/) { chop($param); }
|
||||
if ($param =~ /(\n|\r)$/) { chop($param); }
|
||||
return $param;
|
||||
}
|
||||
Reference in New Issue
Block a user