Re: My first socket question
- From: Jim Gibson <jgibson@xxxxxxxxxxxxxxxxx>
- Date: Thu, 28 Sep 2006 11:40:11 -0700
In article <5npnh25e3ck8md6hauvsh0f1din2ddn3cb@xxxxxxx>, Michele Dondi
<bik.mido@xxxxxxxxxxxxx> wrote:
This is my first C/S socket question, so bear with me if the answer is
obvious or simple. I want to write a program that behaves like a
server if called with no arguments and like a client if supplied some,
sending commands based on those arguments to the server and waiting
for a reply. The following minimal example *does* work for me:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
use constant PORT => 9000;
if (@ARGV) {
my $sock=IO::Socket::INET->new(PeerAddr => 'localhost',
PeerPort => PORT,
Proto => 'tcp') or
die "Cannot connect to server: $!\n";
my $cmd=shift;
print "Client mode, sending command `$cmd'\n";
print $sock "$cmd\r\n";
print scalar <$sock>;
close $sock or die "Cannot disconnect from server: $!\n";
exit;
}
my $server=IO::Socket::INET->new(Listen => 5,
LocalPort => PORT,
Proto => 'tcp') or
die "Cannot start in server mode: $!\n";
print "Server mode\n";
while ( my $client=$server->accept ) {
(my $cmd=<$client>) =~ tr/\r\n//d;
my %answer=(foo => "foo: that's what I wanted!");
print $client
$answer{$cmd} || "Unknown command: `$cmd'", "\r\n";
}
close $server or die "Cannot stop server mode: $!\n";
__END__
Point is, in the *real* application I have in mind, when in server
mode the program will be doing other stuff as well. To be fair, its
main purpose will be doing other stuff. The C/S ipc's purpose will be
exactly of gathering information on how other stuff is being done or
influence how it is. Thus the actual code may be of the form
while (1) {
do_stuff;
???
}
where ??? is the code to handle incoming requests. What should I put
there?
A call to IO::Select::can_read to see if a client is trying to connect.
Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
.
- Prev by Date: Re: FAQ 3.1 How do I do (anything)?
- Next by Date: Re: Ftp via Perl cron job
- Previous by thread: matching date
- Next by thread: can't locate method new IO::Socket::INET
- Index(es):
Relevant Pages
|