use IO::Async::Socket; use IO::Async::Loop; my $loop = IO::Async::Loop->new; my $socket = IO::Async::Socket->new( on_recv => sub { my ( $self, $dgram, $addr ) = @_; print "Received reply: $dgram\n", $loop->stop; }, on_recv_error => sub { my ( $self, $errno ) = @_; die "Cannot recv - $errno\n"; }, ); $loop->add( $socket ); $socket->connect( host => "some.host.here", service => "echo", socktype => 'dgram', )->get; $socket->send( "A TEST DATAGRAM" ); $loop->run;
It is primarily intended for "SOCK_DGRAM" or "SOCK_RAW" sockets (such as UDP or packet-capture); for "SOCK_STREAM" sockets (such as TCP) an instance of IO::Async::Stream is more appropriate.
The "on_recv" handler is invoked once for each packet, datagram, or stream segment that is received. It is passed the data itself, and the sender's address.
The "on_recv_error" and "on_send_error" handlers are passed the value of $! at the time the error occurred. (The $! variable itself, by its nature, may have changed from the original error by the time this handler runs so it should always use the value passed in).
If an error occurs when the corresponding error callback is not supplied, and there is not a subclass method for it, then the "close" method is called instead.
This behaviour allows multiple streams and sockets to be multiplexed simultaneously, meaning that a large bulk transfer on one cannot starve other filehandles of processing time. Turning this option on may improve bulk data transfer rate, at the risk of delaying or stalling processing on other filehandles.
The condition requiring an "on_recv" handler is checked at the time the object is added to a Loop; it is allowed to create a "IO::Async::Socket" object with a read handle but without a "on_recv" handler, provided that one is later given using "configure" before the stream is added to its containing Loop, either directly or by being a child of another Notifier already in a Loop, or added to one.
$socket->send( $data, $flags, $addr )
This method adds a segment of data to be sent, or sends it immediately, according to the "autoflush" parameter. $flags and $addr are optional.
If the "autoflush" option is set, this method will try immediately to send the data to the underlying filehandle, optionally using the given flags and destination address. If this completes successfully then it will have been sent by the time this method returns. If it fails to send, then the data is queued as if "autoflush" were not set, and will be flushed as normal.
$socket->connect( host => $hostname, service => $service, socktype => 'dgram', ... )
$socket->bind( service => 12345, socktype => 'dgram', )->get;