Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: UDP server

by ahunter (Monk)
on Jul 11, 2000 at 21:39 UTC ( #22045=note: print w/ replies, xml ) Need Help??


in reply to UDP server

What's more, accept is meaningless in the context of a UDP socket (it's packet-based, not connection-based). You never receive a connect request on a UDP socket...

All you need to do to make a UDP socket is bind it to the appropriate port, and sysread the packets from it. Maximum packet size is 64k or the size you specify to sysread, whichever is smaller. Untested, but try this:

use strict; use IO::Socket; my $socket=IO::Socket::INET->new(LocalAddr => 'localhost', LocalPort => 2224, Proto => 'udp') or die "socket: $!"; while ((my $length=sysread($socket, my $buffer, 65536)) != 0) { die "sysread: $!" if (!defined($length)); # $buffer contains the received packet }
From perusing the IO::Socket code, it looks like it'll do the right thing.

To send a packet, use this (NOTE: this uses the perl 5.6.0 form of syswrite. In previous versions, you need to supply a length argument):

use strict; use IO::Socket; my $socket=IO::Socket::INET->new(PeerAddr => 'localhost', PeerPort => 2224, Proto => 'udp') or die "socket: $!"; syswrite($socket, "Hello, there\n");

Andrew.

Update: Oops, should have mentioned this, but use recv instead of sysread if you want to know the source of your packets ;-) (sysread still works, though)

Update II: I'm really not on form - the while (sysread) stuff in the first example is probably bad perl - if sysread returns undef, you'll get a warning, *and* the die condition will be skipped. D'oh. Try this instead:

my $length; while (defined($length=sysread($socket, my $buffer, 65536)) && $length + != 0) { ... } die "sysread: $!" if (!defined($length));
This shouldn't warn due to the short-circuit nature of &&...


Comment on Re: UDP server
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://22045]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2014-12-20 01:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (94 votes), past polls