oernii has asked for the wisdom of the Perl Monks concerning the following question:
use IO::Socket; use Term::ReadLine; ##################################### # Server Script: # Copyright 2003 (c) Philip Yuson # this program is distributed according to # the terms of the Perl license # Use at your own risk ##################################### $local = IO::Socket::INET->new( Proto => 'tcp', # protocol LocalAddr => 'localhost:8081', # Host and port to lis +ten to # Change the port if 8 +081 is being used Reuse => 1 ) or die "$!"; ##################################### # Server Script: # Copyright 2003 (c) Philip Yuson # this program is distributed according to # the terms of the Perl license # Use at your own risk ##################################### $local = IO::Socket::INET->new( Proto => 'tcp', # protocol LocalAddr => 'localhost:8081', # Host and port to lis +ten to # Change the port if 8 +081 is being used Reuse => 1 ) or die "$!"; $local->listen(); # listen $local->autoflush(1); # To send response immediately print "At your service. Waiting...\n"; my $addr; # Client handle while ($addr = $local->accept() ) { # receive a request print "Connected from: ", $addr->peerhost(); # Display mess +ages print " Port: ", $addr->peerport(), "\n"; my $result; # variable for Result #while (<$addr>) { # Read all messages from client ## (Assume all valid numbers) #last if m/^end/gi; # if message is 'end' ## then exit loop #print "Received: $_"; # Print received message #print $addr $_; # Send received message back ## to verify #$result += $_; # Add value to result #} $term = new Term::ReadLine('Simple Perl calc'); $prompt = "Enter your arithmetic expression: "; #$OUT = $term->OUT || STDOUT; while ( defined ($_ = $term->readline($prompt)) ) { $res = eval($_), "\n"; warn $@ if $@; print $OUT $res, "\n" unless $@; $term->addhistory($_) if /\S/; } chomp; # Remove the <CR> if (m/^end/gi) { # You need this. Otherwise if # the client terminates abruptly # The server will encounter an # error when it sends the result back # and terminate my $send = "result=$result"; # Format result messag +e print $addr "$send\n"; # send the result mess +age print "Result: $send\n"; # Display sent message } print "Closed connection\n"; # Inform that connection # to client is closed close $addr; # close client print "At your service. Waiting...\n"; # Wait again for next +request }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: IO::Socket and Term::Readline
by pbeckingham (Parson) on Mar 13, 2004 at 18:14 UTC |