收听端口并转发并向api发送数据

时间:2016-12-14 13:09:42

标签: php bash sockets curl

我有一个php脚本,它侦听特定端口并使用curl调用API。问题是当客户端数量增加时它会挂起。所以我想使用bash脚本来做同样的事情。由于linux将使用速度将快速和服务器不会挂起。请指导我完成整个过程。

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '0.0.0.0';
$port = 5002;

$con = mysqli_connect("0.0.0.0","agilemte_soft","As123456","agilemte_soft");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }

        list($IMEI,$Date,$time,$RFID)=explode(",",$buf);
        $IMEI=substr ( $IMEI , 1); 
        echo $RFID;
        if(empty($RFID))
        {
            $time=substr ( $time ,0,-1);
        }

        if(empty($Date))
        {
            $Date="000000";
            $time="000000";
        }
        echo "$time";
        $temp=str_split($Date,2);
        $Date=implode("-", $temp);
        $abcd=str_split($time,2);
        $time=implode(":", $abcd);

        echo "$time";
        $Date=$Date." ".$time;
        echo "$Date";
        $final =  DateTime::createFromFormat('d-m-y H:i:s' ,$Date);
        echo $final->format('Y-m-d H:i:s');
        $Date= $final->format('Y-m-`enter code here`d H:i:s');
        $fina = new DateTime();
        $dt= $fina->format('Y-m-d H:i:s');
        echo "IMEI= $IMEI, Date=$Date, Time= $dt, RFID=$RFID \n";
        mysqli_query($con,"Insert into device_signal values ('$IMEI','$Date','$dt','$RFID')");

    } while (true);
    socket_close($msgsock);
} while (true);
mysqli_close($con);
socket_close($sock);
?>

而不是用CURL替换mysql

0 个答案:

没有答案