прочитать ответ от сокет-сервера и сохранить в базу данных - PullRequest
0 голосов
/ 05 мая 2018

Я новичок в программировании сокетов. У меня есть GPS-трекер, который подключается и отправляет данные на определенный публичный сервер: порт через GPRS-соединение. Я получаю результат на терминале.

Я хочу знать, как я могу получить этот ответ в некоторой переменной, чтобы я мог сохранить эти записи в базе данных в режиме реального времени.

Вот код.

require_once("SocketServer.class.php"); // Include the File
$server = new SocketServer("xxx.xx.x.xxx",8153); // Create a Server binding to the given ip address and listen to port 31337 for connections
$server->max_clients = 10; // Allow no more than 10 people to connect at a time
$server->hook("CONNECT","handle_connect"); // Run handle_connect every time someone connects
$server->hook("INPUT","handle_input"); // Run handle_input whenever text is sent to the server
$server->infinite_loop(); // Run Server Code Until Process is terminated.


function handle_connect(&$server,&$client,$input)
{
    SocketServer::socket_write_smart($client->socket,"String? ","");
}
function handle_input(&$server,&$client,$input)
{
    // You probably want to sanitize your inputs here
    $trim = trim($input); // Trim the input, Remove Line Endings and Extra Whitespace.

    if(strtolower($trim) == "quit") // User Wants to quit the server
    {
        SocketServer::socket_write_smart($client->socket,"Oh... Goodbye..."); // Give the user a sad goodbye message, meany!
        $server->disconnect($client->server_clients_index); // Disconnect this client.
        return; // Ends the function
    }

    $output = strrev($trim); // Reverse the String
echo "output is".$trim;
    SocketServer::socket_write_smart($client->socket,$output); // Send the Client back the String
    SocketServer::socket_write_smart($client->socket,"String? ",""); // Request Another String
}

SocketServer.class.php

http://www.phpclasses.org/browse/file/31975.html

Эта строка не печатает результат на терминале

echo "output is".$trim;

Я тоже это пробовал

$myfile = fopen("file.txt", "w") or die("Unable to open file!");
   fwrite($myfile, $trim);
fclose($myfile);

и файл остается пустым

1 Ответ

0 голосов
/ 08 мая 2018

Перейдите на SocketServer.class.php и найдите этот код

enter image description here

результат находится в этой переменной $input. Поэтому, если вы хотите сохранить данные в базе данных, добавьте свой код в другую часть.

        if($input == null){
            $this->disconnect($i);
        }else{
            SocketServer::debug("{$i}@{$this->clients[$i]->ip} --> {$input}");
            $data= $input;           
            //add your code here

Примечание : автор обновил код своей библиотеки. Вот новый код https://github.com/navarr/Sockets

...