【问题标题】:read a response from socket server and save into database从套接字服务器读取响应并保存到数据库中
【发布时间】:2018-10-15 18:26:16
【问题描述】:

我是套接字编程的新手。我有一个 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);

文件保持为空

【问题讨论】:

  • 你的意思是它已经是 $trim 是一个变量,并且内容在一个变量中。所以在$trim 之后将其保存在您的数据库中。在函数之前打开文件顶部的数据库连接,并在函数中使用它,使用 global $dbConnection; 然后 $dbConnection->prepair() / $dbConnection->query()
  • 我知道如何处理数据库。但是当我这样做时 echo "output is".$trim;它不显示“输出是”,然后是结果
  • 你知道这个包已经很老了,现在可以使用不是吗?7 years ago 你最好使用支持 Async 的库,就像 PHP 7 一样,https://github.com/dazzle-php/socket

标签: php sockets socketserver


【解决方案1】:

转到SocketServer.class.php 并查找此代码

结果在这个变量$input中。因此,如果您想将数据保存到数据库中,请在 else 部分添加您的代码。

        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

【讨论】:

    猜你喜欢
    • 2018-07-10
    • 2018-06-25
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多