| Код | my $SOCK = undef;
$SOCK = set_connect(host, port) or die "can't set connect to $host $port";
while(1) { if (is_data($SOCK)) { my $data = ''; get_data($SOCK, \$data); #распарсить $data #что нибудь сделать с $data } }
sub is_data { my ($SOCK) = @_; my $rin = ''; my $rout = 0; vec($rin, fileno($SOCK), 1) = 1; my $nfound = select($rout=$rin, undef, undef, .8); return $nfound > 0; }
sub set_connect { my ($host, $port) = @_; my $proto = getprotobyname('tcp'); local *S; my $handle = *S; socket($handle, PF_INET, SOCK_STREAM, $proto); my $sin = sockaddr_in($port,inet_aton($host)); connect($handle,$sin) || return undef; my $old_fh = select($handle); $| = 1; # don't buffer output select($old_fh); return $handle; }
#$data - ref sub get_data { my ($handle, $data, $size) = @_; my $len = 512; my $rv = 1; while (1) { my $buf = ''; my $r = sysread($handle, $buf, $len);
if (!defined($r)) { $rv = undef; last; } ${$data} .= $buf; if ($size && length(${$data}) >= $size) { last; } elsif ($r == 0) { last; } elsif ($r < $len) { my $rin = ''; my $rout = ''; vec($rin, fileno($handle), 1) = 1; my $nfound = select($rout=$rin, undef, undef, .2); last if ($nfound <= 0); } }
return $rv; }
|
|