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

namespace PhpLife\App\Api\Controller;


use PhpLife\App\Api\Controller;
use PhpLife\App\Api\Package\Database\Server;

class Ping extends Controller
{

    /**
     * 执行逻辑
     * @return mixed
     */
    protected function main()
    {
        $data=Server::select();
        foreach ($data as $val) {
            $ip=$val['ip'];
            $port=$val['port'];
            $status=$this->check($ip, $port);
            if ($val['status']!=$status){
                Server::update(['status' => $status], ['id'=>$val['id']]);
            }
        }
    }

    /**
     * @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;
    }
}