File: iodemo-inet.pl

package info (click to toggle)
vdk2 2.4.0-5.6
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 6,448 kB
  • sloc: cpp: 26,950; sh: 10,942; ansic: 9,220; makefile: 605; perl: 113
file content (79 lines) | stat: -rwxr-xr-x 1,300 bytes parent folder | download | duplicates (9)
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
#!/usr/bin/perl -w

use strict;
use IO::Socket;
use IO::Select;
use IO::Handle;

sub showsock($$)
{
    my ($s,$flg) = @_;
    my $res = '';

    if($flg & 1)
    {
	$res .=  $s->sockhost . ',' . $s->sockport;
    }
    if($flg == 3)
    {
	$res .= " to ";
    }
    if($flg & 2)
    {
	$res .= $s->peerhost . ',' . $s->peerport;
    }
    $res;
}

my ($lsn, $flag, $fh, $buf, $sel, @ready);

$SIG{INT} = sub {print "Close on SIGINT\n"; $lsn->close(); exit()};

sub cleansock($)
{
    my $fh = $_[0];
    $sel->remove($fh);
    $fh->close();
}

my $port = shift || 'iodemo';

$lsn = new IO::Socket::INET(Listen => 1,
			    LocalPort => $port,
			    Proto => 'tcp',
			    Reuse => 1,
			    Type => SOCK_STREAM) or die "bind $!";

$sel = new IO::Select or die "select $!";

$sel->add($lsn);

print "Listening on ", showsock ($lsn, 1),"\n";

while(@ready = $sel->can_read) 
{
    foreach $fh (@ready) 
    {
	if($fh == $lsn)
	{
	    my $ns = $fh->accept;
	    $sel->add($ns);
	    print "\nConnect ", showsock ($ns, 3), "\n";
	}
	else
	{
	    if($fh->recv($buf, 256, 0), $buf)
	    {
	      print "From ", showsock ($fh, 2), " : ", $buf;
	      $fh->send((length($buf)-1)." :> ".$buf, 0);
	    }
	    else
	    {
		print "Close by ", showsock ($fh, 2), "\n";		
		cleansock($fh);
	    }
	}
    }
}