Hej!
Nedenstaaende er et tcp client script baseret paa eksemplerne i perlipc
dokumentationen.
Tager noget paa stdin (koerer i en pipe) og sender det til et server
script.
For at undgaa at holde forbindelsen aaben hele tiden laver jeg lidt
detect paa hvornaar indholdet starter og stopper og lukker den efter
sidste linie. Dette virker og goer at en given forbindelse kun er aaben
i et par sekunder hvert 5. minut (som er intervallet for stdin data).
.....meeen det er jo en lidt grim loesning, saa jeg taenkte at det ville
vaere meget mere elegant hvis jeg slet ikke tjekkede indholdet, men
istedet lukkede forbindelsen efter f.eks. 10 sekunders inaktivitet og
aabnede den ved aktivitet.
How to do that in Perl ?
Scriptet :
#!/usr/bin/perl -w
# 2001-01-11-jfn StatDB client script for Symbel (Solaris) & Collect
(Tru64).
use strict;
use Socket;
sub logmsg
{
print STDERR "$0 $$: @_ at ", scalar localtime, "\n";
};
my ($remote, $port, $iaddr, $paddr, $protocol, $socket, $connection);
# The remote host where the StatDB server script is located.
$remote = shift || 'statdb';
# The port on the remote host where the StatDB server script is
listening on.
$port = shift || 551234; # random port
if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') } logmsg "No
port." unless $port;
$iaddr = inet_aton($remote) || logmsg "Host \"$remote\" can not be
resolved";
$paddr = sockaddr_in($port, $iaddr);
$protocol = getprotobyname('tcp');
$socket = 0;
$connection = 0;
while (<>)
{
SWITCH:
{
# If the STDIN line is the first in a output from
Collect/Symbel then create a TCP connection.
(/^#### RECORD/ || /^---------------------------- System
Misc Summary ---------------------------/) && do
{
($socket = socket(SOCK, PF_INET, SOCK_STREAM,
$protocol)) || logmsg "$!";
if ($socket)
{
($connection = connect(SOCK, $paddr)) ||
logmsg "$!";
};
};
# If a TCP connection exist, then send what is recieved
at STDIN to the TCP socket.
if ($connection)
{
print SOCK $_;
};
# If the STDIN line is the last in a output from
Collect/Symbel, then destroy the TCP connection.
(/^tty:/ || /^Number of xsdtab\[\] slots per segment/)
&& do
{
if ($connection)
{
close (SOCK) || logmsg "$!";
$connection = 0;
};
};
last SWITCH;
};
};
# If the last STDIN line wasn't a proper termination line, then destroy
the TCP connection anyway.
if ($connection)
{
close (SOCK) || logmsg "$!";
};
exit;
Sent via Deja.com
http://www.deja.com/