Beispiel #1
0
 function setCenterSocket($ip, $port)
 {
     $this->centerSocket = new \swoole_client(SWOOLE_SOCK_UDP);
     $this->centerSocket->connect($ip, $port);
     $this->centerHost = $ip;
     $this->centerPort = $port;
 }
Beispiel #2
0
 public function connect($config)
 {
     $connected = $this->client->connect($config['host'], $config['port'], $config['timeout']);
     if (false == $connected) {
         throw new ConnectionException(socket_strerror($this->client->errCode), $this->client->errCode);
     }
     $this->setConnected();
 }
 public function run(Promise &$promise)
 {
     $cli = new \swoole_client(SWOOLE_TCP, SWOOLE_SOCK_ASYNC);
     $urlInfo = parse_url($this->url);
     $timeout = $this->timeout;
     if (!isset($urlInfo['port'])) {
         $urlInfo['port'] = 80;
     }
     $httpParser = new \HttpParser();
     $cli->on("connect", function ($cli) use($urlInfo, &$timeout, &$promise) {
         $cli->isConnected = true;
         $host = $urlInfo['host'];
         if ($urlInfo['port']) {
             $host .= ':' . $urlInfo['port'];
         }
         $req = array();
         $req[] = "GET {$this->url} HTTP/1.1\r\n";
         $req[] = "User-Agent: PHP swAsync\r\n";
         $req[] = "Host:{$host}\r\n";
         $req[] = "Connection:close\r\n";
         $req[] = "\r\n";
         $req = implode('', $req);
         $cli->send($req);
     });
     $cli->on("receive", function ($cli, $data = "") use(&$httpParser, &$promise) {
         $ret = $httpParser->execute($data);
         if ($ret !== false) {
             Timer::del($cli->sock);
             $cli->isDone = true;
             if ($cli->isConnected()) {
                 $cli->close();
             }
             $promise->accept(['http_data' => $ret]);
         }
     });
     $cli->on("error", function ($cli) use(&$promise) {
         Timer::del($cli->sock);
         $promise->accept(['http_data' => null, 'http_error' => 'Connect error']);
     });
     $cli->on("close", function ($cli) use(&$promise) {
     });
     if ($this->proxy) {
         $cli->connect($this->proxy['host'], $this->proxy['port'], 0.05);
     } else {
         $cli->connect($urlInfo['host'], $urlInfo['port'], 0.05);
     }
     $cli->isConnected = false;
     if (!$cli->errCode) {
         Timer::add($cli->sock, $this->timeout, function () use($cli, &$promise) {
             @$cli->close();
             if ($cli->isConnected) {
                 $promise->accept(['http_data' => null, 'http_error' => 'Http client read timeout']);
             } else {
                 $promise->accept(['http_data' => null, 'http_error' => 'Http client connect timeout']);
             }
         });
     }
 }
Beispiel #4
0
 /**
  * Connect client to server
  *
  * @return $this
  */
 public function connect()
 {
     $this->socket = new \swoole_client(SWOOLE_SOCK_TCP);
     if (!$this->socket->connect($this->host, $this->port)) {
         return false;
     }
     $this->socket->send($this->createHeader());
     return $this->recv();
 }
Beispiel #5
0
 function connect($host, $port, $timeout = 30)
 {
     $this->sock = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     $this->sock->set(['open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 2000000]);
     if ($this->sock->connect($host, $port, $timeout) === false) {
         $this->errCode = $this->sock->errCode;
         return false;
     } else {
         return true;
     }
 }
 public function connect($client)
 {
     $this->socket = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $this->socket->on('Connect', array($client, 'onConnect'));
     $this->socket->on('Receive', array($client, 'onReceive'));
     $this->socket->on('Close', array($client, 'onClose'));
     $this->socket->on('Error', array($client, 'onError'));
     if (!$this->socket->connect($this->host, $this->port)) {
         return false;
     }
     return true;
 }
 public function sendData($tc, $c)
 {
     $client = new swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC);
     $client->on("connect", function ($cli) use($tc) {
         $cli->send($tc->data);
     });
     $client->on('close', function ($cli) {
     });
     $client->on('error', function ($cli) {
     });
     $client->on("receive", function ($cli, $data) use($c) {
         $cli->close();
         $tc = $c->send($data);
         if ($tc instanceof TestClient) {
             $this->sendData($tc, $c);
         } else {
             unset($c);
         }
     });
     if ($client->connect($tc->ip, $tc->port, $tc->timeout)) {
         // if (intval($tc ->timeout) >0) {
         //     swoole_timer_after(intval($tc ->timeout) * 1000, function() use($client){
         //         if ($client ->isConnected()) {
         //             $log = "timeout \n";
         //             error_log($log,3,'/tmp/timeout.log');
         //             $client ->close();
         //             $this ->callback('timeout');
         //         }
         //     });
         // }
     }
 }
Beispiel #8
0
 public static function query($sql)
 {
     $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     $client->connect('127.0.0.1', 9509, 0.5, 0);
     $client->send($sql);
     return $client->recv();
 }
 public function sendData(callable $callback)
 {
     $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $client->on("connect", function ($cli) {
         $cli->send($this->data);
     });
     $client->on('close', function ($cli) {
     });
     $client->on('error', function ($cli) use($callback) {
         $cli->close();
         call_user_func_array($callback, array('r' => 1, 'key' => $this->key, 'error_msg' => 'conncet error'));
     });
     $client->on("receive", function ($cli, $data) use($callback) {
         $cli->close();
         call_user_func_array($callback, array('r' => 0, 'key' => $this->key, 'data' => $data));
     });
     if ($client->connect($this->ip, $this->port, $this->timeout)) {
         if (intval($this->timeout) > 0) {
             swoole_timer_after(intval($this->timeout) * 1000, function () use($client, $callback) {
                 if ($client->isConnected()) {
                     $client->close();
                     call_user_func_array($callback, array('r' => 2, 'key' => '', 'error_msg' => 'timeout'));
                 }
             });
         }
     }
 }
Beispiel #10
0
 function onConnect($serv, $fd, $from_id)
 {
     $socket = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     echo microtime() . ": Client[{$fd}] backend-sock[{$socket->sock}]: Connect.\n";
     $socket->on('connect', function (swoole_client $socket) {
         echo "connect to backend server success\n";
     });
     $socket->on('error', function (swoole_client $socket) {
         echo "connect to backend server fail\n";
         $this->serv->send($this->backends[$socket->sock]['client_fd'], "backend server not connected. please try reconnect.");
         $this->serv->close($this->backends[$socket->sock]['client_fd']);
         $socket->close();
     });
     $socket->on('close', function (swoole_client $socket) {
         echo "backend connection close\n";
     });
     $socket->on('receive', function (swoole_client $socket, $data) {
         //PHP-5.4以下版本可能不支持此写法,匿名函数不能调用$this
         //可以修改为类静态变量
         $servinst->send($this->backends[$socket->sock]['client_fd'], $data);
     });
     if ($socket->connect('61.135.169.125', 80, 1)) {
         $this->backends[$socket->sock] = array('client_fd' => $fd, 'socket' => $socket);
         $this->clients[$fd] = array('socket' => $socket);
     }
 }
Beispiel #11
0
function test_client()
{
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
    //同步阻塞
    if (!$client->connect('127.0.0.1', 10000)) {
        exit("connect fail\n");
    }
    if (empty($argv[1])) {
        $loop = 1;
    } else {
        $loop = intval($argv[1]);
    }
    for ($i = 0; $i < $loop; $i++) {
        $client->send(str_repeat("A", 600) . $i);
        $data = $client->recv(7000, 0);
        if ($data === false) {
            echo "recv fail\n";
            break;
        }
        //echo "recv[$i]",$data,"\n";
    }
    //echo "len=".strlen($data)."\n";
    // $client->send("HELLO\0\nWORLD");
    // $data = $client->recv(9000, 0);
    $client->close();
    var_dump($data);
    unset($client);
}
Beispiel #12
0
 private function getClientObj()
 {
     $key = $this->getConfigObjKey();
     $clientKey = $this->serverConfig[$key]["ip"] . "_" . $this->serverConfig[$key]["port"];
     //set the current client key
     $this->currentClientKey = $clientKey;
     if (!isset(self::$client[$clientKey])) {
         $client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
         $client->set(array('open_length_check' => 1, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 1024 * 1024 * 2, 'open_tcp_nodelay' => 1));
         if (!$client->connect($this->serverConfig[$key]["ip"], $this->serverConfig[$key]["port"], self::SW_RECIVE_TIMEOUT)) {
             //connect fail
             $errorCode = $client->errCode;
             if ($errorCode == 0) {
                 $msg = "connect fail.check host dns.";
                 $errorCode = -1;
             } else {
                 $msg = socket_strerror($errorCode);
             }
             //put the fail connect config to block list
             $this->serverConfigBlock[$key] = 1;
             throw new \Exception($msg, $errorCode);
         }
         self::$client[$clientKey] = $client;
     }
     //success
     return self::$client[$clientKey];
 }
Beispiel #13
0
 /**
  * 发送数据
  * @param string $data
  * @return unknown
  */
 public function sendData($data)
 {
     if (empty($this->client)) {
         $this->client = new \swoole_client(SWOOLE_SOCK_TCP);
     }
     if (!$this->client->connect($this->ip, $this->port, -1)) {
         exit("connect failed. Error: {$this->client->errCode}\n");
     }
     if (\is_array($data) || \is_object($data)) {
         $data = \json_encode($data);
     }
     $data = StringUtil::encryStr($data, ApiConfig::ENCRYTP_DECRYPT_SALT);
     $this->client->send($data);
     $result = $this->client->recv();
     return StringUtil::decryStr($result, ApiConfig::ENCRYTP_DECRYPT_SALT);
 }
Beispiel #14
0
 /**
  * send message by swoole
  * @param string $content the command
  * return boolean true if shut down the swoole_client successfully
  */
 private function sendtagbyswoole($content)
 {
     $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     $client->connect('127.0.0.1', 8888, 0.5, 0);
     $client->send($content);
     return $client->close();
 }
Beispiel #15
0
 /**
  * connect to swoole server then send data
  *
  * @return string
  */
 public static function client()
 {
     $return = FALSE;
     $client = new \swoole_client(SWOOLE_SOCK_TCP);
     // set eof charactor
     $client->set(['open_eof_split' => TRUE, 'package_eof' => self::EOFF]);
     // listen on
     $client->on('connect', '\\CI_Swoole\\Client::on_connect');
     $client->on('receive', '\\CI_Swoole\\Client::on_receive');
     $client->on('error', '\\CI_Swoole\\Client::on_error');
     $client->on('close', '\\CI_Swoole\\Client::on_close');
     // connect
     $client->connect(self::HOST, self::PORT, 10);
     // send data
     if ($client->isConnected()) {
         $post = serialize(static::$post);
         $post .= self::EOFF;
         $issend = $client->send($post);
     }
     // receiv data
     if (isset($issend) && $issend) {
         $return = @$client->recv();
         $return = str_replace(self::EOFF, '', $return);
         $return = unserialize($return);
     }
     $client->close();
     unset($client);
     return $return;
 }
Beispiel #16
0
 public function createBackend()
 {
     $backend = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $backend->on('connect', function ($cli) {
         echo "backend connect.\n";
     });
     $backend->on('receive', function ($cli, $data) {
         echo "backend receive.\n";
         $fd = (int) $cli->sock;
         if (!empty($this->b2c[$fd]['fd'])) {
             $this->server->send($this->b2c[$fd]['fd'], $data);
         }
     });
     $backend->on('close', function ($cli) {
         if (!empty($cli)) {
             $this->backendReconnect($cli);
             //$this->clearClient((int)$cli->sock, $from_client=false);
         }
     });
     $backend->on('error', function ($cli) {
         echo "error\n";
     });
     $backend->connect($this->backend_info['ip'], $this->backend_info['port']);
     return $backend;
 }
 public function sendData(callable $callback)
 {
     $client = new swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC);
     $client->on("connect", function ($cli) {
         $this->isConnect = true;
         $cli->send($this->data);
     });
     $client->on('close', function ($cli) {
         $this->isConnect = false;
     });
     $client->on('error', function ($cli) use($callback) {
         $this->isConnect = false;
         $cli->close();
         call_user_func_array($callback, array('r' => 1, 'key' => $this->key, 'error_msg' => 'conncet error'));
     });
     $client->on("receive", function ($cli, $data) use($callback) {
         $this->isConnect = false;
         $cli->close();
         call_user_func_array($callback, array('r' => 0, 'key' => $this->key, 'data' => $data));
     });
     if ($client->connect($this->ip, $this->port, $this->timeout)) {
         if (intval($this->timeout) > 0) {
             swoole_timer_after(intval($this->timeout) * 1000, function () use($client, $callback) {
                 if ($this->isConnect) {
                     //error_log(__METHOD__." client ===== ".print_r($client,true),3,'/tmp/client.log');
                     $client->close();
                     call_user_func_array($callback, array('r' => 2, 'key' => '', 'error_msg' => 'timeout'));
                 }
             });
         }
     }
 }
Beispiel #18
0
 public function send(callable $callback)
 {
     $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $client->on("connect", function ($cli) {
         $cli->send($this->data);
     });
     $client->on('close', function ($cli) {
     });
     $client->on('error', function ($cli) use($callback) {
         $cli->close();
         call_user_func_array($callback, array('r' => 1, 'key' => $this->key, 'calltime' => $this->calltime, 'error_msg' => 'conncet error'));
     });
     $client->on("receive", function ($cli, $data) use($callback) {
         $this->calltime = microtime(true) - $this->calltime;
         $cli->close();
         call_user_func_array($callback, array('r' => 0, 'key' => $this->key, 'calltime' => $this->calltime, 'data' => $data));
     });
     if ($client->connect($this->ip, $this->port, $this->timeout, 1)) {
         $this->calltime = microtime(true);
         if (floatval($this->timeout) > 0) {
             $this->timer = swoole_timer_after(floatval($this->timeout) * 1000, function () use($client, $callback) {
                 $client->close();
                 \SysLog::error(__METHOD__ . " TIMEOUT ", __CLASS__);
                 $this->calltime = microtime(true) - $this->calltime;
                 call_user_func_array($callback, array('r' => 2, 'key' => '', 'calltime' => $this->calltime, 'error_msg' => 'timeout'));
             });
         }
     }
 }
Beispiel #19
0
function send()
{
    $pid = posix_getpid();
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
    //异步非阻塞
    $client->on("connect", function (swoole_client $cli) use($pid) {
        $data = microtime(true);
        lg("[{$pid}] Send: {$data}", __LINE__);
        $cli->send($data);
    });
    $client->on("receive", function (swoole_client $cli, $data) use($pid) {
        lg("[{$pid}] Received: {$data}", __LINE__);
        $cli->close();
    });
    $client->on("error", function (swoole_client $cli) use($pid) {
        $cli->close();
        //lg("[$pid] error then conn close", __LINE__);
        exit(0);
    });
    $client->on("close", function (swoole_client $cli) use($pid) {
        //lg("[$pid] conn close", __LINE__);
    });
    $client->connect('127.0.0.1', 8001, 0.5);
    //lg("[$pid] create conn succ", __LINE__);
    exit(0);
}
 public function connect()
 {
     if (false === ($uri = parse_url($this->_socket))) {
         throw new \Exception("Invalid socket uri.");
     }
     $timeout = array_key_exists('timeout', $this->_options) ? $this->_options['timeout'] : 5;
     switch ($uri['scheme']) {
         case 'tcp':
             $this->_client = new \swoole_client(SWOOLE_TCP);
             if (!$this->_client->connect($uri['host'], $uri['port'], $timeout)) {
                 throw new \Exception("Connected failed.");
             }
             break;
         default:
             throw new \Exception("Unsupported socket scheme.");
     }
 }
Beispiel #21
0
 function __construct($ip = '127.0.0.1', $port = 9510, $timeout = 2.0)
 {
     $client = new swoole_client(SWOOLE_SOCK_TCP);
     $client->set(array('open_eof_check' => true, 'package_eof' => self::EOF));
     if (!$client->connect($ip, $port, $timeout)) {
         throw new Exception("cannot connect to server [{$ip}:{$port}].");
     }
     $this->client = $client;
 }
 public function __construct()
 {
     $client = new swoole_client(SWOOLE_SOCK_UDP);
     //默认是同步,第二个参数可以选填异步
     //发起网络连接
     $client->connect('0.0.0.0', 9504, 0.5);
     $client->send('demo');
     echo $client->recv();
 }
Beispiel #23
0
 public function clientAction()
 {
     $client = new swoole_client(SWOOLE_SOCK_TCP);
     $client->connect('192.168.80.140', 9021, 0.5);
     $client->send('hello world!');
     echo $client->recv();
     $client->close();
     return false;
 }
Beispiel #24
0
function getClient()
{
    $client = new swoole_client(SWOOLE_SOCK_TCP);
    if (!$client->connect('127.0.0.1', 9501, -1)) {
        exit("connect failed. Error: {$client->errCode}\n");
    }
    $res = $client->getSocket();
    return $client;
}
Beispiel #25
0
 function onReceive($serv, $fd, $from_id, $data)
 {
     $socket = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     if ($socket->connect('127.0.0.1', 8002, 0.5)) {
         $socket->send($data);
         $serv->send($fd, $socket->recv(8192, 0));
     }
     //unset($socket);
     $serv->close($fd);
 }
Beispiel #26
0
/**
 * 批量请求
 * @param array $request_buffer_array ['ip:port'=>req_buf, 'ip:port'=>req_buf, ...]
 * @return multitype:unknown string
 */
function multiRequest($request_buffer_array)
{
    \Statistics\Lib\Cache::$lastSuccessIpArray = array();
    $client_array = $sock_to_ip = $ip_list = array();
    foreach ($request_buffer_array as $address => $buffer) {
        list($ip, $port) = explode(':', $address);
        $ip_list[$ip] = $ip;
        $client = new swoole_client(SWOOLE_TCP | SWOOLE_KEEP, SWOOLE_SOCK_SYNC);
        $client->connect($ip, $port);
        if (!$client) {
            continue;
        }
        $client_array[$address] = $client;
        $client_array[$address]->send(encode($buffer));
        $sock_to_address[(int) $client->sock] = $address;
    }
    $read = $client_array;
    $write = $except = $read_buffer = array();
    $time_start = microtime(true);
    $timeout = 0.99;
    // 轮询处理数据
    while (count($read) > 0) {
        foreach ($read as $client) {
            $address = $sock_to_address[(int) $client->sock];
            $buf = $client->recv();
            if (!$buf) {
                unset($client_array[$address]);
                continue;
            }
            if (!isset($read_buffer[$address])) {
                $read_buffer[$address] = $buf;
            } else {
                $read_buffer[$address] .= $buf;
            }
            // 数据接收完毕
            if (($len = strlen($read_buffer[$address])) && $read_buffer[$address][$len - 1] === "\n") {
                unset($client_array[$address]);
            }
        }
        // 超时了
        if (microtime(true) - $time_start > $timeout) {
            break;
        }
        $read = $client_array;
    }
    foreach ($read_buffer as $address => $buf) {
        list($ip, $port) = explode(':', $address);
        \Statistics\Lib\Cache::$lastSuccessIpArray[$ip] = $ip;
    }
    \Statistics\Lib\Cache::$lastFailedIpArray = array_diff($ip_list, \Statistics\Lib\Cache::$lastSuccessIpArray);
    ksort($read_buffer);
    return $read_buffer;
}
Beispiel #27
0
function thread_start(swoole_thread $coroutine)
{
    $serv = $coroutine->serv;
    $data = $serv->recv($fd);
    $socket = new swoole_client(SWOOLE_SOCK_TCP);
    if ($socket->connect('127.0.0.1', 9502, 0.5)) {
        $socket->send("request\n");
        $response = $socket->recv();
    }
    $socket->close();
    $serv->send($fd, "Server: {$response}\n");
}
Beispiel #28
0
function sendToServer($str)
{
    global $server;
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
    if (!$client->connect($server['ip'], $server['port'], -1)) {
        exit("connect failed. Error: {$client->errCode}\n");
    }
    $client->send($str);
    $str = $client->recv();
    $client->close();
    return $str;
}
function dbcp_query($sql)
{
    $link = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
    //TCP方式、同步
    $link->connect('127.0.0.1', 55151);
    //连接
    $link->send($sql);
    //执行查询
    die(var_dump($link->recv()));
    return unserialize($link->recv());
    //这行会报错,注释掉了:PHP Notice:  unserialize(): Error at offset 0 of 292 bytes in /data/htdocs/mysql.swoole.com/mysqlSwooleCli.php on line 6
    //swoole_client类析构时会自动关闭连接
}
Beispiel #30
0
 /**
  * 数据发送
  *
  * @param $msg
  * @return mixed
  */
 public function send($msg)
 {
     $client = new \swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC);
     $client->on('connect', function ($cli) use($msg) {
         try {
             $cli->send($msg);
         } catch (\Exception $e) {
         }
     });
     $client->on("receive", [$this, "onReceive"]);
     $client->on('close', [$this, 'onClose']);
     $client->on('error', [$this, 'onError']);
     return $client->connect($this->host, $this->port, $this->timeOut, true);
 }