| 1 | # -*- perl -*- | ||
| 2 | |||
| 3 | # Copyright (c) 2009 AdCopy | ||
| 4 | # Author: Jeff Weisberg | ||
| 5 | # Created: 2009-Mar-27 15:01 (EDT) | ||
| 6 | # Function: tcp server | ||
| 7 | # | ||
| 8 | # $Id: Server.pm,v 1.3 2010/09/07 15:31:37 jaw Exp $ | ||
| 9 | |||
| 10 | package AC::DC::IO::TCP::Server; | ||
| 11 | use AC::DC::Debug 'tcp'; | ||
| 12 | use Socket; | ||
| 13 | use strict; | ||
| 14 | |||
| 15 | our @ISA = 'AC::DC::IO::TCP'; | ||
| 16 | |||
| 17 | sub new { | ||
| 18 | my $class = shift; | ||
| 19 | my $port = shift; | ||
| 20 | my $nextc = shift; | ||
| 21 | |||
| 22 | my $me = bless { | ||
| 23 | info => "server tcp/$port", | ||
| 24 | nextclass => $nextc, | ||
| 25 | }, $class; | ||
| 26 | |||
| 27 | my $fd; | ||
| 28 | |||
| 29 | socket($fd, PF_INET, SOCK_STREAM, 0); | ||
| 30 | setsockopt($fd, SOL_SOCKET, SO_REUSEADDR, 1); | ||
| 31 | my $i = bind($fd, sockaddr_in($port, INADDR_ANY)); | ||
| 32 | |||
| 33 | fatal( "cannot bind to tcp/$port: $!" ) unless $i; | ||
| 34 | |||
| 35 | listen( $fd, 128 ); | ||
| 36 | $me->init($fd); | ||
| 37 | $me->wantread(1); | ||
| 38 | |||
| 39 | verbose("server started on tcp/$port"); | ||
| 40 | |||
| 41 | return $me; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub _readable { | ||
| 45 | my $me = shift; | ||
| 46 | |||
| 47 | my $newfd; | ||
| 48 | my $i = accept( $newfd, $me->{fd} ); | ||
| 49 | return verbose("tcp accept failed: $!" ) unless $i; | ||
| 50 | |||
| 51 | my $ip = inet_ntoa( (sockaddr_in(getpeername($newfd)))[1] ); | ||
| 52 | debug( "new tcp connection from $ip" ); | ||
| 53 | |||
| 54 | my $next = $me->{nextclass}; | ||
| 55 | $next->new( $newfd, $ip ); | ||
| 56 | } | ||
| 57 | |||
| 58 | |||
| 59 | 1; |