客户端和服务器php套接字

时间:2018-08-02 13:10:31

标签: php sockets

我使用PHP进行地理定位项目,使用套接字我有问题,我解释一下: 客户端(盒式GPS)发送其标识符(IMEI),并等待服务器的应答(消息“ 01”),在接收到(消息“ 01”)后,客户端将数据发送到服务器,服务器将其存储在数据库。在这里,它仅适用于一个客户端,甚至连接了多个客户端,但如果服务器在等待数据GPS客户端(A)时,另一个客户端(B)已连接,则问题出在服务器接收到数据GPS的数据时客户端(A)时,他将使用客户端(B)的名称存储它们,因为在我的代码中,服务器使用最后连接的客户端的名称存储GPS数据。

 <?php
error_reporting(E_ALL);
set_time_limit(0);

$ip='192.168.1.1';
$port=135;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) ;
socket_bind($sock, $ip , $port) ;

socket_listen ($sock);

echo "Waiting for incoming connections... \n";
$tab=array();
$client = array($sock);
while (true)
{
              $read = $client;
              $write=null ;
              $except=null ;
 if(socket_select($read , $write , $except , 0)<1)
              continue;

 if (in_array($sock, $read))
  {
              $client[] = $newsock = socket_accept($sock);
              socket_getpeername($newsock, $address, $port) ;
              echo "Client $address : $port is now connected to us. \n";
              echo "Waiting for incoming data... \n";
              $key = array_search($sock, $read);
              unset($read[$key]);
     }

  foreach ($read as $read_sock)
   {
    $input = socket_read($read_sock, 102401,PHP_BINARY_READ) ;

     if ($input == false)
       {
           $key = array_search($read_sock, $client);
           unset($client[$key]);
           echo "client disconnected.\n";
           continue;
        }
        if(!empty($input))
        {
            if(strlen($input)==17){
            //$input=bin2hex($input) ;
            $input = substr($input,2,strlen($input));

            $imei_verif=$input ;
            echo "Le 1er socket reçu : \n";
            echo  "IMEI =$input"."\n"."length=".strlen($input);


            //$response=hex2bin('01');
            $response='01';
            echo "\n La réponse est 01 \n";
           $len = strlen($response);

           $res_write=socket_send($read_sock ,$response,$len,0);
           echo "GPS informations ....... \n";
           $conn = new mysqli("localhost", "root", "", "fma120");
           $result = $conn->query("SELECT * FROM vehicule WHERE imei='$imei_verif'");
           $outp = $result->fetch_assoc();
           $identifiant= $outp['identifiant'] ;
           $matricule=$outp['matricule'];
           echo $identifiant."\n";
           echo $matricule;
            }



            else {
                echo "Client $address : $port is now connected to us. \n";
                $input=bin2hex($input) ;
                $payload=$input ;
                $crc = substr($payload, strlen($payload) - 8, 8);

                echo "crc = ".$crc ."\n" ;

                $avlDataWithChecks = substr($payload, 16, -8);
                if (substr($avlDataWithChecks, 2, 2) !== substr($avlDataWithChecks, strlen($avlDataWithChecks) - 2, 2))
                {
                    echo "First element count check is different than last element count check \n ";
                    echo " informations = " .$input ."\n" ;

                }

                if(substr($avlDataWithChecks, 2, 2) == substr($avlDataWithChecks, strlen($avlDataWithChecks) - 2, 2) )
                {

                    echo"voila ....................... GPS informations réçu : \n" ;

                    echo"input = ".$input ."\n" ;
                    echo "length=".strlen($input);
                    echo "avlDataWithChecks = ".$avlDataWithChecks ."\n" ;

                    $numberOfElements = hexdec(substr($avlDataWithChecks, 2, 2));
                    echo "numberOfElements = " .$numberOfElements ."\n" ;
                    $avlData = substr($avlDataWithChecks, 4, -2);


                    $position = 0;
                    $resultData = [];


                    $dateTime = new DateTime();
                    $timestamp = hexdec(substr($avlData, $position, 16)) / 1000;
                    $timestamp+= 7200;
                    echo "timestamp =".$timestamp . "\n";
                    $dateTime -> setTimestamp(intval($timestamp));
                    echo "dateteTime = " .$dateTime->format('U = Y-m-d H:i:s') . "\n";
                    $position += 16;



                    $priority = (int)hexdec(substr($avlData, $position, 2));
                    echo" priority = " .$priority ."\n" ;
                    $position += 2;

                    $longitude = substr($avlData, $position, 8);
                    $longitude = (float)(hexdec($longitude) / 10000000);
                    echo" longitude = " .$longitude ."\n" ;
                    $position += 8;

                    $latitude = substr($avlData, $position, 8);
                    $latitude = (float)(hexdec($latitude) / 10000000);
                    echo" latitude = " .$latitude ."\n" ;
                    $position += 8;

                    $altitude = (int)hexdec(substr($avlData, $position, 4));
                    echo" altitude = " .$altitude ."\n" ;
                    $position += 4;

                    $angle = (int)hexdec(substr($avlData, $position, 4));
                    echo" angle = " .$angle ."\n" ;
                    $position += 4;

                    $satellites = (int)hexdec(substr($avlData, $position, 2));
                    echo" satellites = " .$satellites ."\n" ;
                    $position += 2;

                    $speed = (int)hexdec(substr($avlData, $position, 4));
                    echo" speed = " .$speed ."\n" ;

                    echo "\n La réponse est $numberOfElements \n";


                    $output = sprintf("%08X", $numberOfElements) ;
                    $output2=$output ;
                    echo "avant l'envoie = " .$output2 ."\n" ;

                    $output2 =hex2bin($output2);


                    $len = strlen($output2);

                    $res_write=socket_send($read_sock,$output2,$len,0);

                    echo "apres l'envoie = " .$output2 ."\n" ;
                    //echo $identifiant."\n";
                    //$output2 =hex2bin($output2);


                    $len = strlen($output2);

                    $res_write=socket_send($read_sock ,$output2,$len,0);

                    echo "apres l'envoie = " .$output2 ."\n" ;
                    try
                    {
                        $bdd = new PDO('mysql:host=localhost;dbname=fma120;charset=utf8', 'root', '');
                    }
                    catch(Exception $e)
                    {
                        die('Erreur : '.$e->getMessage());
                    }
                    $bdd->exec("INSERT INTO gps_data(client,matricule,imei, timestamp, longitude, latitude, altitude,angle,satellites,speed,etat,n_of_elem) VALUES('$identifiant','$matricule','$imei_verif', '$timestamp', '$longitude', '$latitude', '$altitude','$angle','$satellites','$speed','0','$numberOfElements')");


                    echo 'Strored in the data base';
                }
                }
        }
    }
}

?>

2 个答案:

答案 0 :(得分:0)

那么您需要存储数据之间的关系,例如,您可以创建一个具有唯一客户端ID作为键的多数组。您还需要存储客户端ID <=>客户端套接字关系。

实现起来并不是那么困难,但是要使所有相关的东西保持井井有条,因此要使其尽可能地容易(我建议创建一个类来保存与连接相关的所有信息,因此您不必遍历抽象套接字资源,而可以进行遍历逻辑连接对象,这使得处理起来更加容易)

例如

class ConnectionInfo
{
    public $Socket;
    public $ID;
}

$Connections = [];
$Connections[$ID]['Socket'] = $Socket;

答案 1 :(得分:0)

问题是gps数据不包含有关客户端的任何信息,所以我无法知道此数据与哪个客户端有关,也许如果我知道消息源的ip地址,然后将其与ip地址进行比较第一次连接的时间(当客户端发送imei时)。
我可以存储第一个连接的ID,但是如何知道同一客户端的第二个连接的信息,以将它们与存储的ID进行比较?