Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

For completeness (or overkill, if you prefer), here's a version with no blocking reads that can handle multiple clients with overlapped packets and only processes a packet when it is complete. It does that by using a hash to store partial data per connection until a complete packet arrives.

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11134663 use warnings; use IO::Socket; use IO::Select; my %data; my $listen = IO::Socket::INET->new( LocalPort => 8080, Listen => 256, Reuse => 1) or die $@; my $sel = IO::Select->new($listen); sub checkforrequests { for my $fh ( $sel->can_read(0) ) # 0 for poll { if( $fh == $listen ) { my $socket = $listen->accept; $data{$socket} = ''; $sel->add( $socket ); print "new client $socket\n"; } elsif( sysread $fh, $data{$fh}, 4096, length $data{$fh} ) { if( $data{$fh} =~ s/^(.*?\n\r?\n)//s ) # any whole HTTP commands { my $command = $1; print $command =~ s/^/got HTTP packet: /gmr; # FIXME process request here print $fh "OK\n"; # FIXME sample response shutdown $fh, 1; $command =~ /quit/ and die "exiting on 'quit' command\n"; } } else { delete $data{$fh}; $sel->remove( $fh ); print "client left $fh\n"; } } } while( 1 ) # your loop as I understand it { select undef, undef, undef, 0.2; # FIXME your non-network stuff checkforrequests(); # this is added to your loop }

In reply to Re^5: Adding simple HTTP controls to existing code by tybalt89
in thread Adding simple HTTP controls to existing code by brachism

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-03-29 06:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found