tags:

views:

135

answers:

2

I need to handle continuous data through TCP and write it to database. I use the following code (suggested by ZZ Coder):

<?php

$fp = fsockopen ("192.168.0.179", 2323);

    if (!$fp) {
        die ("$errstr ($errno)");
    }

    if ($fp) {

$user="root";
$password="12345";
$database="db_name";
mysql_connect('localhost',$user,$password);
@mysql_select_db($database) or die( "Unable to select database");

    $point=false;
    $status="";
    $fix=0;
    while (!$point) {
        $string=@fgets($fp, 4096);

    switch (substr($string,0,6)) {
        case "\$GPRMC" :
        list($sentence, $time, $status, $latitude, $NS, $longitude, $EW, $speed, $course, $date, $magvar, $magvarEW)= explode(",", trim($string));
        mysql_query("INSERT INTO gps_data (time, course) VALUES ('$time', '$course')");
        break;

        case "\$GPGGA" :
        list($sentence, $time, $latitude, $NS, $longitude, $EW, $fix, $nbsat, $HDOP, $altitude,,,,,)= explode(",", trim($string));
        break;

        default :
        break;
    }

        if ($status=="A" and $fix == 1){
            $point=true;
        }
    }

    fclose ($fp);
    mysql_close();

    }

    else {
        print "Fatal error\n";
    }

?>

Questions

  1. How do I start and stop this server?

  2. How do I make it work nonstop (hours/days/weeks) because right now it stops executing at some point.

  3. What happens if 10/20/100/1000 trackers connect and start sending data to 192.168.0.179:2323 (server)?

A: 

Regarding 2:

The following lines of code

if ($status=="A" and $fix == 1){
        $point=true;
}

seems to cause it to break from the while loop when the GPS acquired a lock. If that is the case your program will stop when the GPS acquired a lock.

phsiao
A: 
  1. You need to run the program using the PHP command line tool, i.e. /usr/bin/php server.php. To stop it, kill it with kill(1).
  2. As Shawn Hsiao writes: the program terminates when it gets the terminate command from the server.
  3. You only provide the code of the client, not of the server, so it is difficult to tell. However, in general, there is nothing wrong with having hundreds of clients connect to a single server.
Martin v. Löwis
Am I doing something wrong, because I thought this was a "server" (receives data and writes it to db) and my gps tracker was a "client" (sends data to 192.168.0.179:2323)?
Josh
In socket programming, the one who listens for incoming requests is the server (such as the web server, on port 80); the one who connects is the client (such as the web browser). fsockopen is a client function. To write a server in PHP, you need to use functions like `socket_listen` and `socket_accept`. If your setup works at all, your GPS tracker doesn't send data *to* 2323, but *from* 2323.
Martin v. Löwis
Oh, I see. It was working probably, because my gps simulator is working from the same port. Thanks a lot for your explanation!
Josh