-
Notifications
You must be signed in to change notification settings - Fork 1
/
echo-server-io.pl
executable file
·80 lines (60 loc) · 1.91 KB
/
echo-server-io.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env perl
use 5.10.1;
use strict;
use warnings;
use IO::Handle;
use IO::Socket ('CRLF', 'AF_INET');
use constant MY_ECHO_PORT => 3000;
use constant MY_ADDRESS => '127.0.0.1';
$/ = CRLF;
my( $bytes_out,
$bytes_in ) = (0, 0);
my $quit = 0;
$SIG{INT} = sub {
my $sig = shift;
STDERR->print( "\nTerminated by $sig\n" );
STDERR->print( "\nbytes_sent: $bytes_out, bytes_recieved: $bytes_in\n\n" );
$quit++;
};
my $port = shift || MY_ECHO_PORT;
my $protocol = getprotobyname 'tcp';
my $socket = IO::Socket::INET->new( 'LocalPort' => $port,
'Listen' => 20,
'Reuse' => 1,
'Timeout' => 60*60 )
or die "$!\n";
#socket $socket, AF_INET, SOCK_STREAM, $protocol or die "$!\n";
#setsockopt $socket, SOL_SOCKET, SO_REUSEADDR, 1 or die "$!\n";
#my $server_addr = sockaddr_in $port, (INADDR_ANY or inet_aton MY_ADDRESS);
warn "Waiting for incoming connections on port $port...\n"; #if(
# bind($socket, $server_addr) &&
# listen($socket, SOMAXCONN)
# ) or die "$!\n";
while(! $quit ) {
# my $session = new IO::Handle;
next unless my $session = $socket->accept;
# next unless my $client_addr = accept $session, $socket ;
my $client_addr = gethostbyaddr($session->peeraddr, AF_INET)
or $session->peerhost;
my $port = $session->peerport;
# my( $port,
# $packed_client_addr ) = sockaddr_in $client_addr;
print "Connection from [$client_addr, $port]\n";
$session->print("Welcome to the echo server!$/")
and $session->flush() or warn "$!\n";
# Process client input here
while( <$session> ) {
$bytes_in += length $_;
chomp $_;
my( $msg ) = $_ =~ /^([\w|\s|\'|\"|\!|\?|\.|\,]+)/;
next if(! $msg );
STDOUT->print( $msg ."$/" ) or warn "$!\n";
$session->print("You said: $msg $/")
and $session->flush() or warn "$!\n";
$bytes_out += length $_;
}
print $session "Come back soon!$/";
print "Connection from [$client_addr, $port] closed\n";
close $session;
}
close $socket;