<?php
/**
 * Created by PhpStorm.
 * User: chendeben
 * Date: 2018/8/31
 * Time: 下午9:35
 */

namespace PhpLife\App\Script\Controller;


use PhpLife\App\Script\Controller;
use PhpLife\App\Api\Package\Database\Server as ServerTable;

class Server extends Controller
{

    /**
     * 执行逻辑
     */
    protected function main()
    {
        $i = 0;
        while (true) {
            $data = ServerTable::select();
            foreach ($data as $val) {
                $ip = $val['ip'];
                $port = $val['port'];
                $status = $this->check($ip, $port);
                if ($status == 1) {
                    echo $ip . "\t可用\r\n";
                }
                if ($val['status'] != $status) {
                    ServerTable::update(['status' => $status], ['id' => $val['id']]);
                }
            }
            echo "第" . $i . "次执行完毕\r\n";
            sleep(60);
        }

    }

    /**
     * @param string $ip ip
     * @param int $port 端口
     * @return int 返回状态
     */
    public
    function check($ip, $port)
    {
        $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_set_nonblock($sock);
        socket_connect($sock, $ip, $port);
        socket_set_block($sock);
        $status = socket_select($r = array($sock), $w = array($sock), $f = array($sock), 2);
        return $status;
    }
}