UDP Client/Server
###################### UDP Datagram Socket Demo #######################
#!/usr/bin/perl -w
# This is the client!!
use IO::Socket;
use constant MAXBYTES => scalar 80;
$socket = IO::Socket::INET->new( PeerPort => 3711,
PeerAddr => "challenger.atc.fhda.edu",
Type => SOCK_DGRAM,
Proto => 'udp')
or
die "Could not open socket!\n";
while (1)
{
print "Want the time (y/n)? ";
$line = <STDIN>;
if ($line !~ /^\s*(y(es)?|no?)\s*$/i)
{
print "Illegal response! Try again!\n";
next;
}
last if $line =~ /^\s*no?\s*$/i;
# Wake up the server by satisfying the recv on its end.
$socket->send("junk") or die "Client send: $!\n";
# We want the receive to die if we don't get the time within 5 seconds.
# It illustrates how to make one request attempt die without killing the
# entire client. Most useful in a UDP client.
eval
{
local $SIG{ALRM} = sub {die "No response from server!\n"};
alarm 5;
$socket->recv($inline, MAXBYTES);
print "Got \"$inline\" from server!\n";
alarm 0;
1; # Value for eval code block on normal exit.
}
}
# Note: A die statement in an eval makes the eval block die, *not* the
# entire client.
# This is the server!!
#!/usr/bin/perl -w
use IO::Socket;
use constant MAXBYTES => scalar 80;
$socket = IO::Socket::INET->new(LocalPort => 3711,
Type => SOCK_DGRAM,
Proto => 'udp')
or
die "Could not open socket!\n";
# Notice that there are no processes created and no signals handled!
# UDP is a *much* easier protocol which is used to supply quick, short
# services. It is not as reliable as TCP. However, since it is a
# connectionless protocol, there is no need to trap SIGPIPE. Since
# there are no processes, there's no need to trap delinquent clients
# with SIGALRM and no need for zombie clearance with SIGCHLD.
while (1)
{
eval{
$socket->recv($data, MAXBYTES) or die "Server recv: $!\n";
1;
};
next if $@; # If eval error variable set, skip the send.
chomp($data = localtime);
eval{
$socket->send($data) or die "Server send: $!\n";
1;
}
}
############################## UDP Sessions Below ###########################
$ userv.pl&
[1] 22952
$ uclient.pl
Want the time (y/n)? dfdfdf
Illegal response! Try again!
Want the time (y/n)?
Illegal response! Try again!
Want the time (y/n)? yES
Got "Mon Aug 30 18:44:08 1999" from server!
Want the time (y/n)? y
Got "Mon Aug 30 18:44:10 1999" from server!
Want the time (y/n)? noe
Illegal response! Try again!
Want the time (y/n)? nO
$ uclient.pl
Want the time (y/n)? y
Got "Mon Aug 30 18:44:43 1999" from server!
Want the time (y/n)? n
$