#!/usr/bin/perl use strict; use Tie::File; use IO::Socket; use Socket qw(:DEFAULT :crlf); $/ = CRLF; #use constant DEFAULT_HOST =>'localhost'; #use constant DEFAULT_HOST =>'192.169.212.50'; use constant DEFAULT_HOST =>'192.168.178.23'; use constant DEFAULT_PORT =>'4712'; use constant MAX_MSG_LEN => 100; use constant TIMEOUT => 2; my $host = shift ||DEFAULT_HOST; my $port = shift ||DEFAULT_PORT; my $counter=0; my @array_file; my $protocol = getprotobyname('udp'); $port = getservbyname($port, 'udp') unless $port =~ /^\d+$/; my $data; my $sendung; #my $startzeit = scalar localtime; my $startzeit; my $timeout = 0; my $hilfe = 0; #Variante 1 #socket(SOCK, AF_INET, SOCK_DGRAM, $protocol) or die "socket() gescheitert: $!"; #my $dest_addr = sockaddr_in($port, inet_aton($host)); #Variante 2 my $sock = IO::Socket::INET->new(Proto=>$protocol, PeerAddr=>"$host:$port") or die $@; ## Sende-Empfangsschleife ########## while(1) { fill_with_tie(); ## Sendedaten aus Datei lesen print "Laenge sendung: length($sendung) \n\n"; if ( length($sendung) == 0 ) { $sendung = 'init'; } # if print "sendung: $sendung\n\n"; #Variante 1 #send(SOCK, $sendung, 0, $dest_addr) or die "send() gescheitert: $!\n"; #Variante 2 $sock->send($sendung) or die "sendung gescheitert: $!\n"; #=pod $startzeit = scalar time(); print "start: $startzeit \n"; $hilfe = $startzeit +3 ; print "hilfe: $hilfe \n"; $timeout = scalar time(); unless ( $hilfe < $timeout ) { #sleep(4); print "in Schleife \n\n"; $timeout = scalar time(); print "timeout:: $timeout \n"; $sock->recv($data, MAX_MSG_LEN) or die "empfang gescheitert $!\n"; # recv(SOCK, $data, MAX_MSG_LEN, 0) or die "receive() gescheitert $!"; } #=cut =pod eval { local $SIG{ALRM} = sub { die "Timeout\n" }; alarm(TIMEOUT); $sock->recv($data, MAX_MSG_LEN) or die "empfang gescheitert $!\n"; alarm(0); }; if ($@) { die $@ unless $@ eq "Timeout\n"; warn "Timeout !!\n"; } # if =cut fill_empfang_file($data); ## Empfang in Datei schreiben chomp($data); print "Empfangen: $data \n"; sleep(3); } # while #Variante 2 $sock->close; sub fill_with_tie { my $file = "meinfile.txt"; #my $file="empfangsfile.txt"; my $line; my $elem; my $stempel = scalar localtime; $sendung =''; if ( -e $file ) { tie @array_file, "Tie::File", $file || die $!; foreach $elem (@array_file) { chomp $elem; $sendung= $sendung ."$elem"; #$liste->insert("end",$elem); } ## foreach untie @array_file; $sendung = $stempel . " :::: \n" . $sendung; } else { print "Kann $file nicht oeffnen $!$/"; } ## if -s $file } ## fill_with_tie ################# sub fill_empfang_file { #my $file = "meinfile.txt"; my $file="empfangsfile.txt"; my $line = @_[0]; my $elem; print "Operator: $line \n"; open (EMPFANG, ">>$file") or die "Kann $file nicht oeffnen $!\n"; print EMPFANG "$line\n"; close(FILE); } ## fill_empfang_file ##############