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; } }
/** * 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; }
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]; }
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; }
function eof(Swoole_Benchmark $bc) { static $client = null; static $i; $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" => "\r\n\r\n")); $end = microtime(true); $conn_use = $end - $start; $bc->max_conn_time = $conn_use; $i = 0; //echo "connect {$bc->server_url} \n"; 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; } /*--------写入Sokcet-------*/ $data = str_repeat('A', rand(100, 200)) . "\r\n\r\n"; 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; /*--------读取Sokcet-------*/ $i++; $ret = $client->recv(); if (empty($ret)) { echo $bc->pid, "#{$i}", " is lost\n"; return false; } elseif (strlen($ret) != strlen($data)) { echo "#{$i}\tlength error\n"; var_dump($ret); echo "-----------------------------------\n"; var_dump($data); } $end = microtime(true); $read_use = $end - $start; if ($read_use > $bc->max_read_time) { $bc->max_read_time = $read_use; } return true; }
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; }
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; }
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)); } }
private function getClientObj($ip = "", $port = "") { $connectHost = ""; $connectPort = ""; //if not spc will random if ($ip == "" && $port == "") { $key = $this->getConfigObjKey(); $clientKey = $this->serverConfig[$key]["ip"] . "_" . $this->serverConfig[$key]["port"]; //set the current client key $this->currentClientKey = $clientKey; $connectHost = $this->serverConfig[$key]["ip"]; $connectPort = $this->serverConfig[$key]["port"]; } else { //using spec $clientKey = trim($ip) . "_" . trim($port); //set the current client key $this->currentClientKey = $clientKey; $connectHost = $ip; $connectPort = $port; } 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($connectHost, $connectPort, \DoraDRPC\Base\DoraConst::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]; }
/** * 连接到服务器 * @param SOA_Result $retObj * @return bool * @throws \Exception */ protected function connectToServer(SOA_Result $retObj) { $ret = false; //循环连接 while (count($this->servers) > 0) { $svr = $this->getServer(); //基于Swoole扩展 if ($this->haveSwoole) { $key = $svr['host'] . ':' . $svr['port'] . '-' . $retObj->index; $socket = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP, SWOOLE_SOCK_SYNC, $key); $socket->set(array('open_length_check' => true, 'package_max_length' => $this->packet_maxlen, 'package_length_type' => 'N', 'package_body_offset' => SOAServer::HEADER_SIZE, 'package_length_offset' => 0)); $ret = $socket->connect($svr['host'], $svr['port'], $this->timeout); $socketFd = $socket->sock; } elseif ($this->haveSockets) { $socket = new TCP(); $socket->try_reconnect = false; $ret = $socket->connect($svr['host'], $svr['port'], $this->timeout); $socketFd = intval($socket->getSocket()); } else { $socket = new Stream(); $ret = $socket->connect($svr['host'], $svr['port'], $this->timeout); $socketFd = intval($socket->getSocket()); } //连接被拒绝,证明服务器已经挂了 //TODO 如果连接失败,需要上报机器存活状态 if ($ret === false and $socket->errCode == 111) { $this->onConnectServerFailed($svr); unset($socket); } else { $retObj->socket = $socket; $retObj->server_host = $svr['host']; $retObj->server_port = $svr['port']; //使用SOCKET的编号作为ID $retObj->id = $socketFd; break; } } return $ret; }
<?php $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞 $client->set(array('open_eof_check' => true, 'package_eof' => "\r\n\r\n")); $client->_count = 0; $client->on("connect", function (swoole_client $cli) { swoole_timer_clear($cli->timer); $cli->send("GET / HTTP/1.1\r\n\r\n"); //$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"); }); $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', 9501); $client->timer = swoole_timer_after(1000, function () use($client) { echo "socket timeout\n"; $client->close();
private function getClientObj() { //config obj key $key = ""; //if not spc will random switch ($this->connectMode) { case 1: $key = $this->getConfigObjKey(); $clientKey = $this->serverConfig[$this->connectGroup][$key]["ip"] . "_" . $this->serverConfig[$this->connectGroup][$key]["port"]; //set the current client key $this->currentClientKey = $clientKey; $connectHost = $this->serverConfig[$this->connectGroup][$key]["ip"]; $connectPort = $this->serverConfig[$this->connectGroup][$key]["port"]; break; case 2: //using spec $clientKey = trim($this->connectIp) . "_" . trim($this->connectPort); //set the current client key $this->currentClientKey = $clientKey; $connectHost = $this->connectIp; $connectPort = $this->connectPort; break; default: throw new \Exception("current connect mode is unknow", -1); break; } 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($connectHost, $connectPort, DoraConst::SW_RECIVE_TIMEOUT)) { //connect fail $errorCode = $client->errCode; if ($errorCode == 0) { $msg = "connect fail.check host dns."; $errorCode = -1; } else { $msg = \socket_strerror($errorCode); } if ($key !== "") { //put the fail connect config to block list $this->serverConfigBlock[$this->connectGroup][$key] = 1; } throw new \Exception($msg . " " . $clientKey, $errorCode); } self::$client[$clientKey] = $client; } //success return self::$client[$clientKey]; }
<?php $client = new swoole_client(SWOOLE_TCP | SWOOLE_ASYNC); $client->count = 0; function sendPackage(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; echo "send length=" . strlen($sendData) . ", SerId={$data['int1']}\n"; $cli->send($sendData); } $client->set(array('open_length_check' => 1, 'dispatch_mode' => 1, 'worker_num' => 4, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 2000000)); $client->on('connect', function (swoole_client $cli) { echo "Connected.\n"; sendPackage($cli); }); $client->on('receive', function (swoole_client $cli, $data) { $req = unserialize(substr($data, 4)); echo ">> received length=" . strlen($data) . ", SerId: {$req['int1']}\n"; $cli->count++; if ($cli->count > 10) { $cli->close(); } swoole_timer_after(1000, function () use($cli) { sendPackage($cli); }); }); $client->on('close', function ($cli) { echo "Client: Close.\n";
<?php if (!empty($_SERVER['DEV_MODE']) && !empty($_REQUEST['fpm'])) { return; } $config = is_file($configFile = dirname(__DIR__) . '/app/config/production/service.php') ? include $configFile : []; $runDir = isset($config['run_dir']) ? $config['run_dir'] : '/tmp/phwoolcon/'; if (!is_file($portFile = $runDir . 'service-port.php')) { return; } $port = (include $portFile); $sockFile = $runDir . 'service-' . $port . '.sock'; $client = new swoole_client(SWOOLE_UNIX_STREAM); $client->set(['open_length_check' => true, 'package_max_length' => 262144, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4]); if (!@$client->connect($sockFile, 0, 20)) { return; } $request = ['request' => $_REQUEST, 'cookies' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES]; $request = serialize($request); $request = pack('N', $length = strlen($request)) . $request; if ($length > 2097152) { foreach (str_split($request, 1048576) as $chunk) { $client->send($chunk); } } else { $client->send($request); } $response = $client->recv(); $client->close(); if ($response === false) { header('Bad Gateway', true, 502);
protected function asyncSendAndReceive($request, $use) { $self = $this; $noop = function ($client) { }; $on_connect = function ($client) use($self, $request, $use) { if (!$self->send($client, $request)) { $self->sendAndReceiveCallback('', new \Exception(socket_strerror($client->errCode)), $use); } }; $on_error = function ($client) use($self, $use) { $self->sendAndReceiveCallback('', new \Exception(socket_strerror($client->errCode)), $use); }; $on_receive = function ($client, $data) use($self, $use, $noop) { swoole_timer_clear($client->timer); $client->on("connect", $noop); $client->on("error", $noop); $client->on("receive", $noop); $client->timer = swoole_timer_after($self->pool_timeout, function () use($client) { $client->close(); }); array_push($this->pool, $client); try { $self->sendAndReceiveCallback(substr($data, 4), null, $use); } catch (\Exception $e) { } }; $client = null; while (count($this->pool) > 0) { $client = array_pop($this->pool); if ($client->isConnected()) { break; } } if ($client == null || !$client->isConnected()) { $client = new \swoole_client($this->type, SWOOLE_SOCK_ASYNC); $setting = array_replace($this->setting, self::$default_setting); if (!isset($setting['package_max_length'])) { $setting['package_max_length'] = $this->return_bytes(ini_get('memory_limit')); } if ($setting['package_max_length'] < 0) { $setting['package_max_length'] = 0x7fffffff; } $client->set($setting); $client->on("connect", $on_connect); $client->on("error", $on_error); $client->on("receive", $on_receive); $client->on("close", $noop); $client->connect($this->host, $this->port); } else { swoole_timer_clear($client->timer); $client->on("error", $on_error); $client->on("receive", $on_receive); if (!$this->send($client, $request)) { $this->sendAndReceiveCallback('', new \Exception(socket_strerror($client->errCode)), $use); } } $client->timer = swoole_timer_after($this->timeout, function () use($client) { $client->close(); }); }
function sendCmdToServ($data) { $client = new swoole_client(SWOOLE_UNIX_STREAM, SWOOLE_SOCK_SYNC); $client->set(array('open_eof_check' => false)); $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; }
/** * [send 异步IO,定时器设置,异常回调] * @param callable $callback [description] * @return [type] [description] */ public function send(callable $callback) { $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $client->on("connect", function ($cli) { $cli->send($this->request); }); $client->on('close', function ($cli) { }); $client->on('error', function ($cli) use($callback) { $cli->close(); $this->calltime = microtime(true) - $this->calltime; 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) { /* 这里的on receivce会被触发多次,耗时和取消定时器都不在这里处理,在packRsp函数里 */ call_user_func_array(array($this, 'packRsp'), array('key' => $cli, 'data' => $data)); }); $this->callback = $callback; $client->set(array('open_eof_check' => false)); if ($client->connect($this->host, $this->port, $this->timeout)) { $this->calltime = microtime(true); if (floatval($this->timeout) > 0) { Timer::add($this->key, $this->timeout, $client, $callback, array('r' => 2, 'key' => $this->key, 'calltime' => $this->calltime, 'error_msg' => $this->host . ':' . $this->port . ' timeout')); } } }
<?php 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"; } $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞 $client->set(array('open_length_check' => 1, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 2000000)); $client->on("connect", function (swoole_client $cli) { send($cli); }); $client->on("receive", function (swoole_client $cli, $data) { $resp = unserialize(substr($data, 4)); echo "recv length=" . strlen($data) . ", SerId={$resp['int1']}\n" . str_repeat('-', 60) . "\n"; // sleep(1); //usleep(200000); //send($cli); }); $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', 9501);
<?php $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞 $client->set(array('socket_buffer_size' => 1024 * 1024 * 2)); $client->_count = 0; $client->on("connect", function (swoole_client $cli) { swoole_timer_clear($cli->timer); $cli->send("GET / HTTP/1.1\r\n\r\n"); //$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"); }); $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', 9501); $client->timer = swoole_timer_after(1000, function () use($client) { echo "socket timeout\n"; $client->close();