J
John Kelly
Stein has an example of UNIX datagram sockets in his Networking book,
but it includes other ideas that, to me, made it hard to see the forest
for the trees. So I distilled it down to the bare essential elements
related to socket setup.
I use a loop with 100,000 iterations to test performance, and get about
40,000 round trips per second. A similar C solution gets about 55,000
round trips per second. Because syscall and context switch overhead is
a limiting factor, the Perl code performs well compared to C.
Please ignore bad practices in this code, it's only intended to show how
to set up the datagram sockets, which to me, seemed mysterious without a
simple example.
--- CLIENT ---
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::UNIX;
my $peer = '/tmp/server.sock';
my $node = '/tmp/client1.sock';
unlink $node;
my $sock = IO::Socket::UNIX->new (
Local => $node,
Peer => $peer,
Type => SOCK_DGRAM
) or die "$!";
my $tn;
my $data;
for ($tn = 1; $tn < 100000; $tn++) {
send ($sock, '1234567890_blah_blah_blah', 0) or die "$!";
recv ($sock, $data, 100, 0) or die "$!";
}
print "tn=$tn\n";
--- SERVER ---
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::UNIX;
my $node = '/tmp/server.sock';
unlink $node;
my $sock = IO::Socket::UNIX->new (
Local => $node,
Type => SOCK_DGRAM
) or die "$!";
my $peer;
my $data;
while (1) {
$peer = recv ($sock, $data, 100, 0);
send ($sock, $data, 0, $peer) || warn "$!";
}
but it includes other ideas that, to me, made it hard to see the forest
for the trees. So I distilled it down to the bare essential elements
related to socket setup.
I use a loop with 100,000 iterations to test performance, and get about
40,000 round trips per second. A similar C solution gets about 55,000
round trips per second. Because syscall and context switch overhead is
a limiting factor, the Perl code performs well compared to C.
Please ignore bad practices in this code, it's only intended to show how
to set up the datagram sockets, which to me, seemed mysterious without a
simple example.
--- CLIENT ---
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::UNIX;
my $peer = '/tmp/server.sock';
my $node = '/tmp/client1.sock';
unlink $node;
my $sock = IO::Socket::UNIX->new (
Local => $node,
Peer => $peer,
Type => SOCK_DGRAM
) or die "$!";
my $tn;
my $data;
for ($tn = 1; $tn < 100000; $tn++) {
send ($sock, '1234567890_blah_blah_blah', 0) or die "$!";
recv ($sock, $data, 100, 0) or die "$!";
}
print "tn=$tn\n";
--- SERVER ---
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::UNIX;
my $node = '/tmp/server.sock';
unlink $node;
my $sock = IO::Socket::UNIX->new (
Local => $node,
Type => SOCK_DGRAM
) or die "$!";
my $peer;
my $data;
while (1) {
$peer = recv ($sock, $data, 100, 0);
send ($sock, $data, 0, $peer) || warn "$!";
}