Question

i have to create a little perl script which is creating an tcp socket and put the input from this socket into an mysql table.

Background: I get Call Data Records from a Siemens Hipath phone system via this TCP Socket. I have to write the data, which is CSV in an DB for future use. The format i get is following: 13.05.14;15:01:14;3;10;00:26;00:00:45;0123456789;;1;

Im new to perl, an have a few "noob" questions :) 1: How is it possible to run that script in background (as deamon) ? 2: The Script is only handling the last line of an deliverd csv line. If there are two lines, it ignores the first line. How can i fix that ? 3: Today i got this output from my script: DBD::mysql::st execute failed: MySQL server has gone away at ./hipath-CDR-Server.pl line 41. What happend there?

Can anyone help me with that maybe easy questions.

This is what i got till now:

#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use IO::Socket::INET;

my $dbh = DBI->connect('DBI:mysql:database=hipathCDR;host=localhost','***','***',{ RaiseError => 1, AutoCommit => 1 }, );

my $sql = 'INSERT INTO calls (Datum,Zeit,Leitung,Teilnehmer,Rufzeit,Gespraechszeit,RufNr,Gebuehr,Typ) VALUES (?,?,?,?,?,?,?,?,?)';
my $sth = $dbh->prepare($sql);

# auto-flush on socket
$| = 1;

# creating a listening socket
my $socket = new IO::Socket::INET (
    LocalHost => '0.0.0.0',
    LocalPort => '4444',
    Proto => 'tcp',
    Listen => 5,
    Reuse => 1
);
die "cannot create socket $!\n" unless $socket;

while(1)
{
    # waiting for a new client connection
    my $client_socket = $socket->accept();

    # get information about a newly connected client
    my $client_address = $client_socket->peerhost();
    my $client_port = $client_socket->peerport();

    # read up to 1024 characters from the connected client
    my $data = "";
    $client_socket->recv($data, 1024);

    chomp ($data);
    my @values = split(';', $data);
    print "Array: @values\n";
    $sth->execute(@values);

    # write response data to the connected client
    $data = "ok";
    $client_socket->send($data);

    # notify client that response has been sent
    shutdown($client_socket, 1);

}

$socket->close();
Was it helpful?

Solution

You have more than one question, I am going to answer the second: Here is howto get all data.

my $data = "";
while ($client_socket->recv($data, 1024)){
  $data .= $_;
}

It would more safer to parse the incoming CSV like data by Text::CSV.

Answer to question three:

Most probably your mysql was unavailable that time.

Answer to question one:

nohup ./script.pl &

Okay, I am just kidding: How can I run a Perl script as a system daemon in linux?

use Proc::Daemon;

Proc::Daemon::Init;

my $continue = 1;
$SIG{TERM} = sub { $continue = 0 };
...
while($continue)
{
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top