MiggyMan has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys, bit of a quick, and possibly obvious one (but hey, i'm stuck so why not ask!), the code below was derived from an example I found on here, when you first connect tcp_connect is aware of the port you're comming in on, the connections will all be persistent so I want to use that port to differentiate between connections, the problem is I can't seem to find away to determine the port from within on_read!
use warnings; use AnyEvent; use AnyEvent::Socket; use AnyEvent::Handle; use Data::Dumper; my $port = 7777; my $cv = AnyEvent->condvar; tcp_server undef, 7777, sub { my ( $fh, $host, $port ) = @_; warn "Accepted connection from $host:$port\n"; create_handle( $fh, 0 ); }; sub create_handle { my ( $socket, $exit_on_close ) = @_; my ( $shandle, $thandle ); my $destroy = sub { $shandle->destroy; $cv->send if $exit_on_close; }; $shandle = AnyEvent::Handle->new( fh => $socket, on_error => $destroy, on_close => $destroy, ); $shandle->on_read( sub { if ( $shandle->rbuf eq "marco" ) { $shandle->push_write("polo"); } print "A\n"; $shandle->rbuf = ''; print $shandle->rbuf; } ); $shandle->on_eof(undef); } $cv->recv;

Replies are listed 'Best First'.
Re: Getting port number with AnyEvent::Socket
by Anonymous Monk on Jun 13, 2010 at 11:34 UTC
      Gives me the listening port rather than the random port the connections comming from!
Re: Getting port number with AnyEvent::Socket
by Khen1950fx (Canon) on Jun 14, 2010 at 01:01 UTC
    I tried it using Socket::Class.
    #!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; use Socket::Class; our $RUNNING : shared = 1; our $Server = Socket::Class->new( 'local_addr' => '127.0.0.1', 'local_port' => '7777', 'listen' => 5, 'blocking' => 0, 'reuseaddr' => 1, ) or die Socket::Class->error; $SIG{'INT'} = \&quit; threads->create( \&server_thread, $Server ); threads->create( \&client_thread, $Server ); while ($RUNNING) { $Server->wait(5); } sub quit { my ($thread); $RUNNING = 0; foreach $thread ( threads->list ) { eval { $thread->join(); }; } $Server->free(); exit(0); } sub server_thread { my ($server) = @_; my ($client); print "Server running at port: ", $server->local_port, "\n"; while ($RUNNING) { $client = $server->accept(); if ( !defined $client ) { last; } elsif ( !$client ) { next; } threads->create( \&client_thread, $client ); } return 1; } sub client_thread { my ($client) = @_; my ( $buf, $got ); print 'Client is running on port ' . $client->remote_port . "\n"; $client->wait(5); $client->free(); threads->self->detach() if $RUNNING; return 1; } quit();