<?php
require dirname(dirname(__FILE__)).'/vendor/autoload.php';
require_once dirname(dirname(__FILE__)) . '/vendor/workerman/Autoloader.php';
require_once dirname(dirname(__FILE__)) . '/vendor/mysql/src/Connection.php';
require_once __DIR__ . '/config.php';


use Workerman\Worker;                             //worker容器类
use Workerman\Connection\AsyncTcpConnection;      //连接异步客户端
use Workerman\MySQL\Connection;                   //连接数据库的类
use Workerman\Lib\Timer;                          //定时器函数

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\ErrorLogHandler;
$task = new Worker();
// 进程启动时异步建立一个到www.baidu.com连接对象，并发送数据获取数据
$task->onWorkerStart = function($task)
{
    // 不支持直接指定http，但是可以用tcp模拟http协议发送数据
    $connection_to_baidu = new AsyncTcpConnection('tcp://47.254.202.24:10009');
    // 当连接建立成功时，发送http请求数据

        $connection_to_baidu->onConnect = function($connection_to_baidu)
        {
            echo "connect success\n";
            $connection_to_baidu->send('{"type":"ping"}' . "\n");
        };
        $connection_to_baidu->onMessage = function($connection_to_baidu, $http_buffer)
        {
            var_dump($http_buffer);
        };
        $connection_to_baidu->onClose = function($connection_to_baidu)
        {
            echo "connection closed\n";
        };
        $connection_to_baidu->onError = function($connection_to_baidu, $code, $msg)
        {
            echo "Error code:$code msg:$msg\n";
        };

    var_dump($connection_to_baidu);
    $connection_to_baidu->connect();
    // 发送给 webserver 服务器  心跳=====================================================

    Timer::add(10, function () use ($connection_to_baidu) {
       $connection_to_baidu->close();

    });
    Timer::add(11, function () use ($connection_to_baidu) {

        $connection_to_baidu->onConnect = function($connection_to_baidu)
        {
            echo "connect success\n";
            $connection_to_baidu->send('{"type":"ping"}' . "\n");
        };
        $connection_to_baidu->onMessage = function($connection_to_baidu, $http_buffer)
        {
            var_dump($http_buffer);
        };
        $connection_to_baidu->onClose = function($connection_to_baidu)
        {
            echo "connection closed\n";
        };
        $connection_to_baidu->onError = function($connection_to_baidu, $code, $msg)
        {
            echo "Error code:$code msg:$msg\n";
        };
        $connection_to_baidu->connect();
    });
};

// 运行worker
Worker::runAll();