Ejemplo n.º 1
0
Archivo: Client.php Proyecto: vimac/zan
 public function close()
 {
     if (!$this->connected) {
         return true;
     }
     return $this->client->close();
 }
Ejemplo n.º 2
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];
 }
Ejemplo n.º 3
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();
 }
Ejemplo n.º 4
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();
 }
Ejemplo n.º 5
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;
}
Ejemplo n.º 6
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;
 }
Ejemplo n.º 7
0
 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();
 }
Ejemplo n.º 8
0
function send(swoole_client $cli)
{
    $data = array('str1' => str_repeat('A', rand(1000, 9000)), 'str2' => str_repeat('B', rand(1000, 9000)), 'str3' => str_repeat('C', rand(1000, 9000)));
    $data['int1'] = rand(100000, 999999);
    $sendStr = serialize($data);
    $sendData = pack('N', strlen($sendStr)) . $sendStr;
    $cli->send($sendData);
    echo "send length=" . strlen($sendData) . ", SerId={$data['int1']}\n";
}
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
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");
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
0
/**
 * 分段发送数据
 *
 * @param swoole_client $client
 * @param string        $data
 * @param int           $chunk_size
 */
function send_chunk(swoole_client $client, $data, $chunk_size = 1024)
{
    $len = strlen($data);
    $chunk_num = intval($len / $chunk_size) + 1;
    for ($i = 0; $i < $chunk_num; $i++) {
        if ($len < ($i + 1) * $chunk_size) {
            $sendn = $len - $i * $chunk_size;
        } else {
            $sendn = $chunk_size;
        }
        $client->send(substr($data, $i * $chunk_size, $sendn));
    }
}
Ejemplo n.º 14
0
 /**
  * 创建一个新的客户端
  */
 static function create()
 {
     $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $client->on("connect", 'G::onConnect');
     $client->on("receive", 'G::onReceive');
     $client->on("error", function (swoole_client $cli) {
         echo "error\n";
     });
     $client->on("close", 'G::onClose');
     $client->connect('127.0.0.1', 9502);
     self::$count++;
     self::putLog("CREATE#" . $client->sock . "\$");
 }
Ejemplo n.º 15
0
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类析构时会自动关闭连接
}
Ejemplo n.º 16
0
 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'));
                 }
             });
         }
     }
 }
Ejemplo n.º 17
0
Archivo: run.php Proyecto: ErosZy/CSF
function long_tcp(Benchmark $bc)
{
    global $send_data, $package_eof;
    static $client = null;
    static $i;
    static $index;
    $start = microtime(true);
    if (empty($client)) {
        $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
        $client->set(array('open_eof_check' => true, "package_eof" => $package_eof));
        $end = microtime(true);
        $conn_use = $end - $start;
        $bc->max_conn_time = $conn_use;
        $i = 0;
        $index = 0;
        if (!$client->connect($bc->server_config['host'], $bc->server_config['port'], 2)) {
            error:
            echo "Error: " . swoole_strerror($client->errCode) . "[{$client->errCode}]\n";
            $client = null;
            return false;
        }
        $start = $end;
    }
    $data = $send_data[$index]["data"] . $package_eof;
    if (!$client->send($data)) {
        goto error;
    }
    $end = microtime(true);
    $write_use = $end - $start;
    if ($write_use > $bc->max_write_time) {
        $bc->max_write_time = $write_use;
    }
    $start = $end;
    $i++;
    if ($i >= $send_data[$index]["num"]) {
        $index++;
    }
    $ret = $client->recv();
    if (empty($ret)) {
        echo $bc->pid, "#{$i}", " is lost\n";
        return false;
    }
    $end = microtime(true);
    $read_use = $end - $start;
    if ($read_use > $bc->max_read_time) {
        $bc->max_read_time = $read_use;
    }
    return true;
}
Ejemplo n.º 18
0
 public static function init()
 {
     if (!self::$client) {
         $client = new swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
         if (!$client->isConnected()) {
             $client->set(array('open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 2000000));
             if (!$client->connect('127.0.0.1', 8996, 1)) {
                 //                    throw new MyException('client connect timeout', ERROR::CONNECTION_TIMEOUT);
                 return false;
             }
         }
         self::$client = $client;
     }
     return self::$client;
 }
Ejemplo n.º 19
0
 public function testSwoole()
 {
     $this->assertTrue(in_array('swoole', get_loaded_extensions()), '缺少swoole extension');
     $cfg = (include ROOT_PATH . '/../config/sysconfig.php');
     $params = array('ip', 'port');
     foreach ($params as $param) {
         $this->assertTrue(array_key_exists($param, $cfg['swooleConfig']) && !empty($cfg['swooleConfig'][$param]), 'swoole缺少' . $param . '配置');
     }
     // 测试连接
     $swoole = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
     $this->assertTrue($swoole->connect($cfg['swooleConfig']['ip'], $cfg['swooleConfig']['port']), 'swoole连接失败');
     // 测试swoole数据传输
     $this->assertTrue($swoole->send(json_encode(array('cmd' => 'checkMobi', 'args' => 18611740380.0))), 'swoole send失败');
     $this->assertTrue(!empty($swoole->recv()), 'swoole recv失败');
 }
Ejemplo n.º 20
0
Archivo: crawl.php Proyecto: ilei/blog
 public function startSwoole()
 {
     $client = new swoole_client(SWOOLE_SOCK_TCP);
     if (!$client->connect('127.0.0.1', 9501)) {
     } else {
         //参照 cli/server控制器理解
         $send = array();
         //发送命令
         $send['cmd'] = 'send';
         $send['object'] = '';
         $send['method'] = 'callback';
         //回调函数的参数
         $client->send(json_encode($send));
         $receive = $client->recv();
     }
 }
Ejemplo n.º 21
0
 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;
 }
Ejemplo n.º 22
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;
 }
Ejemplo n.º 23
0
 function pop()
 {
     if ($this->client->send("POP " . self::EOF)) {
         $result = $this->client->recv();
         if ($result === false) {
             return false;
         }
         if (substr($result, 0, 2) == 'OK') {
             return substr($result, 3, strlen($result) - 3 - strlen(self::EOF));
         } else {
             $this->errMsg = substr($result, 4);
             return false;
         }
     } else {
         return false;
     }
 }
Ejemplo n.º 24
0
function getResponse(swoole_client $client)
{
    $recv = $client->recv();
    if (!$recv) {
        die("Error: recv header failed.\n");
    }
    $respCode = json_decode($recv, true);
    if (!$respCode) {
        die("Error: header json_decode failed.\n");
    }
    if ($respCode['code'] != 0) {
        die("Server: message={$respCode['msg']}.\n");
    } else {
        echo "[FromServer]\t{$respCode['msg']}\n";
    }
    return true;
}
Ejemplo n.º 25
0
 function invokeAsy($sourceType, $fn, $recvfn, $compressType = 0)
 {
     $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
     $client->set(array('open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 2000000));
     $this->client = $client;
     $this->fnData = $fn;
     $this->recvfn = $recvfn;
     $this->sourceType = $sourceType;
     $this->compressType = $compressType;
     $this->client->on('connect', [$this, 'onClientConnect']);
     $this->client->on('receive', [$this, 'onClientReceive']);
     $this->client->on('error', [$this, 'onClientError']);
     $this->client->on('close', [$this, 'onClientClose']);
     if (!$this->client->connect($this->host, $this->port, self::$timeout)) {
         throw new \Exception(socket_strerror($this->client->errCode));
     }
 }
Ejemplo n.º 26
0
 function onReceive($serv, $fd, $from_id, $data)
 {
     $socket = new swoole_client(SWOOLE_SOCK_TCP);
     echo "send data:\n" . $data . "\n";
     if ($socket->connect('www.baidu.com', 80, 1)) {
         $socket->send($data);
         while (1) {
             $recv = $socket->recv(8000, 0);
             echo "recv data:\n" . $recv . "\n";
             if (strlen($recv) > 0) {
                 $serv->send($fd, $recv);
             }
         }
     }
     //         unset($socket);
     //         $serv->close($fd);
 }
Ejemplo n.º 27
0
 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'));
                 }
             });
         }
     }
 }
Ejemplo n.º 28
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;
 }
Ejemplo n.º 29
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);
     }
 }
Ejemplo n.º 30
0
Archivo: TCP.php Proyecto: RamboLau/tsf
 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'));
             });
         }
     }
 }