Recently, I came across a large perl module, "AnyEvent", which allows the user to run an asynchronous / event-driven program.
The following snippet is created, which works great. The problem is that after it opens and closes many sockets, it quickly exhausted all the client ports ("netstat - ant" indicates that 20,000+ sockets are in TIME_WAIT state).
$hdl = new AnyEvent::Handle ( connect => [$ip, $port], on_connect=> sub { my ($handle, $host, $port, $tmp) = @_;
I wonder if it is possible to create a TCP socket with IO :: Socket :: INET, and then use the newly created socket in AnyEvent :: Handle:
my $sock = IO::Socket::INET->new( Proto => 'tcp', PeerAddr => $ue->{vars}->{ip}, PeerPort => $ue->{vars}->{dstPort}, ReusePort => 1, KeepAlive => 1 ) || die "failed to setup outsock $@ \n"; $hdl = new AnyEvent::Handle ( fh => $sock, on_connect=> sub { my ($handle, $host, $port, $tmp) = @_;
I tried, but it did not work. Please rate any suggestions and comments.
Thanks to ikegami who looked into it and gave an offer. However, it looks like SO_REUSEADDR is not taking effect. Here is the code I used (at his suggestion)
use strict; use warnings; use AnyEvent qw( ); use AnyEvent::Handle qw( ); use AnyEvent::Impl::EV qw( ); use AnyEvent::Socket qw( tcp_connect ); use Socket qw( SOL_SOCKET SO_REUSEPORT SO_REUSEADDR); my $ts = 0; my $trans = 0; my $currentTS; sub transaction { my ($host, $port) = @_; tcp_connect($host, $port, sub { my ($sock) = @_ or die "Can't connect: $!"; my $handle; $handle = AnyEvent::Handle->new( fh => $sock, on_eof => sub { $handle->destroy(); }, on_read => sub { my ($handle) = @_;
My system is Ubuntu 11.04. In the / proc / sys / net / ipv 4 directory, here are the contents of the two files:
% more than tcp_tw_recycle
1
% more than tcp_tw_reuse
1