﻿#!/usr/bin/perl -w

# server4.pl

use strict;
use IO::Socket;

$SIG{CHLD} = sub {wait;};

my $server = IO::Socket::INET->new(
	LocalPort => 8080,
	Type => SOCK_STREAM,
    Reuse => 1,
    Listen => 5) or die "$@\n";

my $client;
     
while ( $client = $server->accept()){ 

    next if my $pid = fork();
    die "Error al crear proceso: $!\n" unless defined $pid;

    my $method = "";
    my $uri = "";
    my $content_length = 0;
        
    while(<$client>){
        last if /^\r\n$/;

        if ( $_ =~ /^(GET|POST) (.*?) HTTP\// ){            
            $method = $1;
            $uri = $2;
        }
        if ( $_ =~ /^Content-Length: ([0-9]+)\r\n$/ ){
            $content_length = $1;
        }
    }

    my $post_body = "";
    read $client, $post_body, $content_length;

    my $resp_html =<<HTML;
HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n
Metodo: $method
<br>
URI: $uri
<br>
Cuerpo POST: $post_body
<hr>
<form action='/' method='POST'>
    val1: <input type='text' name='val1'><br><br>
    val2: <input type='text' name='val2'>
    <input type='submit' value='Enviar POST'>
</form>
HTML

    sleep 10;

    select $client;
    $| = 1; 

    print $client $resp_html;

    close($client);

    exit(fork); 
}
continue{
    close($client);
    kill CHLD => -$$;
}
