Setting Up a UDP Server
Problem
You want to write a UDP server.
Solution
First bind
to the port the server is to be
contacted on. With IO::Socket, this is easily accomplished:
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 recv
function returns the address of the
sender, which you must then decode.
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 ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.