17.5. Setting Up a UDP ServerProblemYou want to write a UDP server. Solution
First use IO::Socket; $server = IO::Socket::INET->new(LocalPort => $server_port, Proto => "udp") or die "Couldn't be a udp server on port $server_port : $@\n"; Then, go into a loop receiving messages: while ($him = $server->recv($datagram, $MAX_TO_READ, $flags)) { # do something } Discussion
Life with UDP is much simpler than life with TCP. Instead of accepting client connections one at a time and committing yourself to a long-term relationship, take messages from clients as they come in. The Example 17.2 is a small UDP-based server that just sits around waiting for messages. Every time a message comes in, we find out who sent it and send them a message based on the previous message, and then save the new message. Example 17.2: udpqotd#!/usr/bin/perl -w # udpqotd - UDP message server use strict; use IO::Socket; my($sock, $oldmsg, $newmsg, $hisaddr, $hishost, $MAXLEN, $PORTNO); $MAXLEN = 1024; $PORTNO = 5151; $sock = IO::Socket::INET->new(LocalPort => $PORTNO, Proto => 'udp') or die "socket: $@"; print "Awaiting UDP messages on port $PORTNO\n"; $oldmsg = "This is the starting message."; while ($sock->recv($newmsg, $MAXLEN)) { my($port, $ipaddr) = sockaddr_in($sock->peername); $hishost = gethostbyaddr($ipaddr, AF_INET); print "Client $hishost said ``$newmsg''\n"; $sock->send($oldmsg); $oldmsg = "[$hishost] $newmsg"; } die "recv: $!";
This program is easier using IO::Socket than the raw Socket module. We don't have to say where to send the message because the library keeps track of who sent the last message and stores that information away on the You can't use the telnet program to talk to this server. You have to use a dedicated client. One is shown in Example 17.3 . Example 17.3: udpmsg#!/usr/bin/perl -w # udpmsg - send a message to the udpquotd server use IO::Socket; use strict; my($sock, $server_host, $msg, $port, $ipaddr, $hishost, $MAXLEN, $PORTNO, $TIMEOUT); $MAXLEN = 1024; $PORTNO = 5151; $TIMEOUT = 5; $server_host = shift; $msg = "@ARGV"; $sock = IO::Socket::INET->new(Proto => 'udp', PeerPort => $PORTNO, PeerAddr => $server_host) or die "Creating socket: $!\n"; $sock->send($msg) or die "send: $!"; eval { local $SIG{ALRM} = sub { die "alarm time out" }; alarm $TIMEOUT; $sock->recv($msg, $MAXLEN) or die "recv: $!"; alarm 0; 1; # return value from eval on normalcy } or die "recv from $server_host timed out after $TIMEOUT seconds.\n"; ($port, $ipaddr) = sockaddr_in($sock->peername); $hishost = gethostbyaddr($ipaddr, AF_INET); print "Server $hishost responded ``$msg''\n";
This time when we create the socket, we supply a peer host and port at the start, allowing us to omit that information in the
We've added an See Also
The
|
|