/** * 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(); }
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); }
/** * 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; }
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(); }
/** * 发送数据 * @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); }
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; } }
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']); } }); } }
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; }
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"; }
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(); }
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); }
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 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"); }
/** * 分段发送数据 * * @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)); } }
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类析构时会自动关闭连接 }
/** * @param string $data * @param string $type * @param bool $masked * @return bool */ public function send($data, $type = 'text', $masked = false) { switch ($type) { case 'text': $_type = WEBSOCKET_OPCODE_TEXT; break; case 'binary': case 'bin': $_type = WEBSOCKET_OPCODE_BINARY; break; default: return false; } return $this->socket->send(swoole_websocket_server::pack($data, $_type, true, $masked)); }
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失败'); }
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; }
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(); } }
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); }
function send_data() { global $count, $max_send_num, $send_interval; global $url, $port; $pid = posix_getpid(); while (1) { if ($max_send_num < $count) { $count = 1; sleep($send_interval); continue; //exit(0); } $client = new swoole_client(SWOOLE_TCP, SWOOLE_SOCK_ASYNC); $ret = $client->connect($url, $port, 0.5, 1); $client->send("HELLO WORLD\n"); $clients[$client->sock] = $client; while (!empty($clients)) { $write = $error = array(); $read = array_values($clients); $n = swoole_client_select($read, $write, $error, 0.6); if ($n > 0) { foreach ($read as $index => $c) { echo "Recv #{$c->sock}: " . $c->recv() . "\n"; unset($clients[$c->sock]); } } } /* $fp = @stream_socket_client("tcp://{$url}:{$port}", $errno, $errstr, 30); if (!$fp) { exit(1); } $rand = random(); $data = time() . "-{$rand}-{$pid}-{$count}"; fwrite($fp, $data . "\r\n"); lg("c: $data"); fgets($fp, 1024); fclose($fp); $count++; */ usleep(5000); } }
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; }
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); } }
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); }
/** * @param $data * @param bool $json 是否进行JSON串化 * @return bool|mixed */ function request($data) { $pkg = $this->pack($data); $ret = $this->sock->send($pkg); if ($ret === false) { fail: $this->errCode = $this->sock->errCode; return false; } $ret = $this->sock->recv(); if (!$ret) { goto fail; } $json = $this->unpack($ret); //服务器端返回的内容不正确 if (!isset($json['code'])) { $this->errCode = 9001; return false; } return $json; }
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); }
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); }
public function send($data = null) { //锁定状态写入队列 if (!empty($data)) { $this->queue->push($data); } if ($this->reconn) { Trace::debug("*********cli {$this->fd} reconn \n"); $this->cli->connect($this->conf['ip'], $this->conf['port']); $this->reconn = false; $this->lock = true; } if ($this->queue->isEmpty()) { $this->lock = false; } elseif (!$this->lock) { $this->lock = true; $data = $this->queue->shift(); Trace::debug("*********cli {$this->fd} send " . strlen($data) . "\n==================\n" . substr($data, 0, 50) . "...\n=============="); Trace::info(sprintf("Host: %-25s %s", $this->conf['host'], strstr($data, "\n", true))); //;'Host:' . $this->conf['host'] . strstr($data, "\n", true) $this->cli->send($data); } }
return; } if (empty($data['push_data']['commits'])) { //没有提交者 mylog('no commit'); return; } //项目名称 $project = $data['push_data']['repository']['name']; //分支名称 $ref = $data['push_data']['ref']; mylog("{$project}: {$ref} push"); global $config; if (empty($config[$project][$ref])) { mylog("no {$project} {$ref}"); return; } $client = new \swoole_client(SWOOLE_SOCK_UDP); foreach ($config[$project][$ref] as $item) { $client->connect($item['host'], $item['port']); $client->send(json_encode([$project, $ref, $item['path']])); } }); $http->on('workerStart', function ($serv, $workerId) { global $config; if (function_exists('opcache_reset')) { opcache_reset(); } $config = (include __DIR__ . DIRECTORY_SEPARATOR . 'config.php'); }); $http->start();
$_sendStr = $header; } else { // $header = "POST /home/explore/?hello=123&world=swoole#hello HTTP/1.1\r\n"; $header = "POST /post.php HTTP/1.1\r\n"; $header .= "Host: 127.0.0.1\r\n"; $header .= "Referer: http://group.swoole.com/\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2\r\n"; $header .= "Cookie: pgv_pvi=9559734272; efr__Session=uddfvbm87dtdtrdsro1ohlt4o6; efr_r_uname=apolov%40vip.qq.com; efr__user_login=3N_b4tHW1uXGztWW2Ojf09vssOjR5abS4abO5uWRopnm0eXb7OfT1NbIoqjWzNCvodihq9qaptqfra6imtLXpNTNpduVoque26mniKej5dvM09WMopmmpM2xxcmhveHi3uTN0aegpaiQj8Snoa2IweHP5fCL77CmxqKqmZKp5ejN1c_Q2cPZ25uro6mWqK6BmMOzy8W8k4zi2d3Nlb_G0-PaoJizz97l3deXqKyPoKacr6ynlZ2nppK71t7C4uGarKunlZ-s; pgv_si=s8426935296; Hm_lvt_4967f2faa888a2e52742bebe7fcb5f7d=1410240641,1410241802,1410243730,1410243743; Hm_lpvt_4967f2faa888a2e52742bebe7fcb5f7d=1410248408\r\n"; $header .= "RA-Ver: 2.5.3\r\n"; $header .= "RA-Sid: 2A784AF7-20140212-113827-085a9c-c4de6e\r\n"; $_postData = ['body1' => 'swoole_http-server', 'message' => 'nihao']; $_postBody = json_encode($_postData); // $_postBody = http_build_query($_postData); $header .= "Content-Length: " . strlen($_postBody); echo "http header length=" . strlen($header) . "\n"; $header .= "Content-Length: " . (strlen($_postBody) - 2); // $cli->send($header); // usleep(100000); $_sendStr = $header . "\r\n\r\n" . $_postBody; // $_sendStr = "\r\n\r\n" . $_postBody; echo "postBody length=" . strlen($_postBody) . "\n"; } echo "-------------------------Request----------------------------\n"; echo $_sendStr; $cli->send($_sendStr); echo "send " . strlen($_sendStr) . " byte\n"; echo "-------------------------Response----------------------------\n"; $data = $cli->recv(); var_dump($data); exit;