nss12 has asked for the wisdom of the Perl Monks concerning the following question:
use Socket; use strict; use warnings; use IO::Select; use threads; use threads::shared; # Program Options $| = 1; # Whether or not to flush the output - 1 = yes, 0 = no my $HTTP_PORT = 80; # Port to listen to for HTTP requests my $SSL_PORT = 443; # Port to listen to for encrypted HTTP requsts my $USE_THREADING = 0; # Create a new thread for each request #setup the http port for use with interface local *S; socket (S, PF_INET , SOCK_STREAM , getprotobyname('tcp')) or die + "couldn't open socket: $!"; setsockopt (S, SOL_SOCKET, SO_REUSEADDR, 1) or die "No Setting."; bind (S, sockaddr_in($HTTP_PORT, INADDR_ANY)); listen (S, 5) or die + "don't hear anything: $!"; my $ss = IO::Select->new(); $ss -> add (*S); #my $sse = IO::Select->new(); #$sse -> add (*S); if($USE_THREADING){ #asynchronous loop while(1){ #continually grab requests from port my @connections_pending = $ss->can_read(); foreach (@connections_pending) { #grab the header of the request my $fh; my $remote = accept($fh, $_); #get the remote port and ip my($port,$iaddr) = sockaddr_in($remote); my $peeraddress = inet_ntoa($iaddr); #put the remote ip with header my @sendArray = ($fh, $peeraddress); #create a new thread to handle this request my $t = threads->create(\&new_connection, @sendArray); #don't leak memory! $t->detach(); } } } #method called on each new connection sub new_connection { #take the request header from parameter array my $fh = shift; #take the remote ip from parameter array my $remote_addr = shift; #read header in binary binmode $fh; #create a list for header vars my %req; $req{HEADER}={}; my $request_line = <$fh>; my $first_line = ""; while ($request_line ne "\r\n") { unless ($request_line) { close $fh; } chomp $request_line; #add the remote ip var to header $req{HEADER}{"remote-ip"} = $remote_addr; unless ($first_line) { $first_line = $request_line; my @parts = split(" ", $first_line); if (@parts != 3) { close $fh; } #add method (get/post) to header with objects $req{METHOD} = $parts[0]; $req{OBJECT} = $parts[1]; } else { my ($name, $value) = split(": ", $request_line); $name = lc $name; #add each variable to the list $req{HEADER}{$name} = $value; } $request_line = <$fh>; } #call the HTTP request handler method http_request_handler($fh, \%req); close $fh; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Getting POST data from HTTP Request
by tobyink (Canon) on May 14, 2012 at 06:26 UTC | |
by nss12 (Novice) on May 16, 2012 at 11:48 UTC |