Beispiel #1
0
 public function close()
 {
     if (!$this->connected) {
         return true;
     }
     return $this->client->close();
 }
 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 #3
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 #4
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 #5
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 #6
0
 static function onReceive(swoole_client $cli, $data)
 {
     self::putLog("RECV#" . $cli->sock . "\$");
     $r = rand(0, 100);
     //20%几率关闭连接
     if ($r > 80) {
         self::putLog("CLOSE#" . $cli->sock . "\$");
         $cli->close();
     } elseif ($r > 60) {
         $index = array_rand(self::$clients);
         $_cli = self::$clients[$index];
         self::putLog("CLOSE#" . $_cli->sock . "\$");
         $_cli->close();
     } elseif ($r > 40) {
         $index = array_rand(self::$clients);
         $_cli = self::$clients[$index];
         self::send($_cli);
     } elseif ($r > 20) {
         //不要超过最大客户端数量
         if (count(self::$clients) < self::MAX_CLIENTS) {
             self::create();
         }
     } else {
         self::send($cli);
     }
 }
Beispiel #7
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 #8
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();
 }
 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'));
                 }
             });
         }
     }
 }
 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'));
                 }
             });
         }
     }
 }
 public function __destruct()
 {
     Trace::debug("*********cli {$this->fd} __destruct");
     if (isset($this->cli)) {
         $this->cli->isConnected() && $this->cli->close();
         unset($this->cli);
     }
     unset($this->queue);
 }
Beispiel #12
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 #13
0
 function onReceive($serv, $fd, $from_id, $data)
 {
     $socket = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $socket->on('connect', function (swoole_client $socket) use($data) {
         $socket->send($data);
     });
     $socket->on('error', function (swoole_client $socket) use($serv, $fd) {
         _e("connect to backend server fail", __LINE__);
         $serv->send($fd, "backend server not connected. please try reconnect.");
         $socket->close();
     });
     $socket->on('close', function (swoole_client $socket) use($serv, $fd) {
         $serv->close($fd);
     });
     $socket->on('receive', function (swoole_client $socket, $data) use($serv, $from_id, $fd) {
         $serv->send($fd, $data, $from_id);
         $socket->close();
     });
     $socket->connect('127.0.0.1', 8002, 0.2);
 }
Beispiel #14
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 #15
0
 public function swooleCall($data, $remoteUri = '', $return = 0)
 {
     $address = '127.0.0.1:9588';
     $data2 = json_encode($data);
     if (!empty($remoteUri)) {
         $address = $remoteUri;
     }
     $client = new \swoole_client(SWOOLE_SOCK_TCP);
     $address = explode(':', $address);
     if (!@$client->connect($address[0], $address[1], 20)) {
         return $this->call($data);
     }
     $client->send($data2);
     if ($return) {
         $res = $client->recv();
         $client->close();
         return json_decode($res);
     }
     $client->close();
     return array('code' => 200, 'data' => 0);
 }
Beispiel #16
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;
}
Beispiel #17
0
 public function swooleCall($data, $remoteUri = '', $return = 0)
 {
     $config = DI::getDefault()['config'];
     if (!empty($remoteUri)) {
         $address = explode(':', $remoteUri);
     } else {
         $address = array($config->swoole_api->host, $config->swoole_api->port);
     }
     $client = new \swoole_client(intval($config->swoole_api->protocol));
     if (!@$client->connect($address[0], $address[1], $config->swoole_api->timeout)) {
         return $this->call($data);
     }
     $data['return'] = $return;
     $client->send(json_encode($data));
     if ($return) {
         $res = $client->recv();
         $client->close();
         return json_decode($res, true);
     }
     $client->close();
     return array('code' => 200, 'data' => 0);
 }
Beispiel #18
0
 public function clientrun($queue = null)
 {
     try {
         $this->_setting($queue);
     } catch (Exception $e) {
         throw new \LogicException($e->getMessage());
     }
     $cli = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     //异步
     if (!$cli->connect($this->host, $this->port)) {
         return false;
         exit("connect failed. Error: {$client->errCode}\n");
     }
     $cli->close();
     return true;
 }
 private function exec($cmd)
 {
     $cmd['act'] = 'Telnet';
     $client = new \swoole_client(SWOOLE_TCP, SWOOLE_SYNC);
     if (!$client->connect(C('SERVICE_IP'), C('SERVICE_PORT'), 1) || !$client->send(json_encode($cmd))) {
         return false;
     }
     $c = 5;
     $str = '';
     do {
         $str .= $client->recv();
         $data = json_decode($str, true);
     } while ($c-- > 0 && !isset($data['code']));
     $client->close();
     return $data;
 }
Beispiel #20
0
 public static function handle(array $data)
 {
     Statistic::addPageLog(true);
     //判断格式是否正确
     if (empty($data['event']) || empty($data['data'])) {
         return false;
     }
     $event = $data['event'];
     //判断本类里面是否有对应的方法
     if (!isset(self::$relation[$event])) {
         //收集错误
         return false;
     }
     $relation = self::$relation[$event];
     //给relation中添加唯一key的value,如果添加失败,则收集错误
     if (!self::addValue($relation, $data)) {
         //收集错误
         return false;
     }
     $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     $di = DI::getDefault();
     $statisCountConfig = $di['config']->StatCountServer;
     set_error_handler(function (&$result) {
         $result = false;
     });
     //error为false  表示推送到运维服务器
     if (!@$client->connect($statisCountConfig->host, $statisCountConfig->port, $statisCountConfig->timeout)) {
         //            echo 'count进程连接失败';
         Statistic::addPageLog(false, 'local', 'report', $event, false, '');
         //收集错误
         return false;
     }
     $client->send(json_encode($relation));
     $result = $client->recv();
     $client->close();
     restore_error_handler();
     if (Statistic::parseResult($result)) {
         Statistic::addPageLog(false, 'local', 'report', $event, true, '');
         return true;
     }
     Statistic::addPageLog(false, 'local', 'report', $event, false, '');
     //收集错误
     return false;
 }
Beispiel #21
0
 public function __call($methodName, $arguments)
 {
     $auth = $this->api->getAuth();
     $sendData = \array_merge(array('type' => 'api-call', 'params' => $arguments, 'service' => $this->name, 'method' => $methodName), $auth);
     $sendJson = \json_encode($sendData);
     $sendStr = $this->encryStr($sendJson, $this->encrypt_decrypt_salt);
     $client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
     $client->connect($this->api->getIp(), $this->api->getPort()) or die('连接服务器失败');
     $client->send($sendStr);
     $result = $client->recv();
     $client->close();
     $resultJson = $this->decryStr($result, $this->encrypt_decrypt_salt);
     $resultArr = \json_decode($resultJson, true);
     if ($resultArr['succ']) {
         return $resultArr['data'];
     } else {
         throw new \Exception($resultArr['msg'], 50100, null);
     }
 }
Beispiel #22
0
 /**
  * @brief 发生错误时的回调
  * @param \swoole_client $client
  */
 public function onError(\swoole_client $client)
 {
     $error = array('errno' => \Aha\Network\Client::ERR_UNEXPECT, 'errmsg' => array('errCode' => $client->errCode, 'error' => socket_strerror($client->errCode)), 'package' => $this->_package);
     echo "Redis onError![error]" . serialize($error) . PHP_EOL;
     $callback = $this->_callback;
     $arguments = $this->_arguments;
     $this->_free();
     if ($client->isConnected()) {
         $client->close();
     }
     try {
         call_user_func($callback, false, $arguments['callback'], $this, 'Redis onError');
     } catch (\Exception $ex) {
         echo "Redis onError callback![exception]" . $ex->getMessage() . PHP_EOL;
     }
 }
Beispiel #23
0
    //$cli->sendfile(__DIR__.'/test.txt');
    //$cli->_count = 0;
});
$client->on("receive", function (swoole_client $cli, $data) {
    echo "Receive: {$data}";
    $cli->_count++;
    if ($cli->_count > 10) {
        $cli->close();
        return;
    }
    $cli->send(str_repeat('A', 100) . "\n");
    $cli->finish = true;
});
$client->on("error", function (swoole_client $cli) {
    echo "error\n";
});
$client->on("close", function (swoole_client $cli) {
    echo "Connection close\n";
});
$client->connect('127.0.0.1', 9502);
swoole_timer_after(1000, function () use($client) {
    if ($client->finish) {
        return;
    } else {
        echo "socket timeout\n";
        $client->close();
    }
});
echo "connect to 127.0.0.1:9501\n";
//for PHP5.3-
//swoole_event_wait();
Beispiel #24
0
 /**
  * 析构方法
  */
 public function __destruct()
 {
     if (!empty($this->client)) {
         $this->client->close();
     }
 }
Beispiel #25
0
function short_tcp($bc)
{
    $fp = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
    if (!$fp->connect($bc->server_config['host'], $bc->server_config['port'], 1)) {
        error:
        echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
        return false;
    } else {
        if (!$fp->send($bc->send_data)) {
            goto error;
        }
        $ret = $fp->recv();
        $fp->close();
        if (!empty($ret)) {
            return true;
        } else {
            return false;
        }
    }
    usleep(100);
}
Beispiel #26
0
 /**
  * Disconnect from server
  */
 public function disconnect()
 {
     $this->connected = false;
     $this->socket->close();
 }
Beispiel #27
0
function sendCmdToServ($data)
{
    $client = new swoole_client(SWOOLE_UNIX_STREAM, SWOOLE_SOCK_SYNC);
    $client->connect(uniSockPath, 0);
    $client->send(json_encode($data));
    $ret = $client->recv();
    StartLog(__LINE__ . print_r($ret, true));
    $ret = json_decode($ret, true);
    $client->close();
    return $ret;
}
Beispiel #28
0
<?php

$cli = new swoole_client(SWOOLE_TCP);
if (!$cli->connect("127.0.0.1", 5900, -1)) {
    exit("connect failed. Error:{$cli->errCode}\r\n");
}
$msg_normal = "hello world.";
$msg_length = pack("N", strlen($msg_normal)) . $msg_normal;
$i = 0;
$times = 100;
while ($i < $times) {
    $cli->send($msg_length);
    $i++;
    $data = $cli->recv(4, 1);
    $length = unpack("N", $data)[1];
    $msg = $cli->recv($length, 1);
    echo "receive:{$msg},len:{$length}\r\n";
}
$cli->close();
Beispiel #29
0
 function close()
 {
     $this->cli->close();
 }
Beispiel #30
0
 protected function asyncSendAndReceive($request, $use)
 {
     $self = $this;
     $client = new \swoole_client($this->type, SWOOLE_SOCK_ASYNC);
     $buffer = "";
     $len = "";
     $client->on("connect", function ($cli) use($self, $request, $use) {
         if (!$self->send($cli, $request)) {
             $self->sendAndReceiveCallback('', new \Exception(socket_strerror($cli->errCode)), $use);
         }
     });
     $client->on("error", function ($cli) use($self, $use) {
         $self->sendAndReceiveCallback('', new \Exception(socket_strerror($cli->errCode)), $use);
     });
     $client->on("receive", function ($cli, $data) use($self, &$buffer, &$len, $use) {
         do {
             if (count($buffer) == 0 || is_string($len)) {
                 $left = 4 - strlen($len);
                 if (strlen($data) < $left) {
                     $len .= $data;
                     return;
                 }
                 $len .= substr($data, 0, $left);
                 $len = unpack("N", $len);
                 $len = $len[1];
                 $n = strlen($data) - $left;
             } else {
                 $left = 0;
                 $n = strlen($data);
             }
             if ($n == 0) {
                 $buffer = "";
                 return;
             }
             if ($len == $n) {
                 $response = $buffer . substr($data, $left);
                 $buffer = "";
                 $len = "";
                 try {
                     $self->sendAndReceiveCallback($response, null, $use);
                 } catch (\Exception $e) {
                 }
                 swoole_timer_clear($cli->timer);
                 $cli->close();
                 return;
             }
             if ($len > $n) {
                 $buffer .= substr($data, $left);
                 $len -= $n;
                 return;
             }
             $response = $buffer . substr($data, $left, $len);
             $buffer = "";
             $data = substr($data, $left + $len);
             $len = "";
             try {
                 $self->sendAndReceiveCallback($response, null, $use);
             } catch (\Exception $e) {
             }
         } while (true);
     });
     $client->on("close", function ($cli) {
     });
     $client->connect($this->host, $this->port);
     $client->timer = swoole_timer_after($this->timeout, function () use($client) {
         $client->close();
     });
 }