Friday, July 10, 2009

UDP server in Perl

#!/usr/bin/perl

use strict;
use warnings;

use IO::Socket::INET;
use IO::Handle;

if ($#ARGV <>
die "Argument should be an integer port number\n";
} elsif ($ARGV[0] =~ /\D+/) {
die "Argument should be an integer port number\n";
}

my $Port = $ARGV[0];

my $MySocket = new IO::Socket::INET->new(
LocalPort => $Port,
Proto => 'udp'
) or die "Error opening UDP port $Port $!\n";

print "\nListening on UDP port $Port ...\n\n";

my $MsgText;

open(FILE, ">>udpserver.txt") or die "Error opening udpserver.txt file $!\n";
FILE->autoflush(1);
$MySocket->autoflush();

my $count = 1;
while ($MySocket->recv($MsgText, 4096)) {
print "$count <$MsgText>\n";
print FILE "$count <$MsgText>\n";
$count++;
}

close(FILE);

__END__

No comments: