Commit 440e7462 authored by 杨培's avatar 杨培

支持 hyeprf jsonrpc-tcp-length-check 协议。

parent f6f39318
......@@ -210,9 +210,10 @@ class Client
if (!isset($connections[$instance->rpcServer])) {
$srv = parse_url($instance->rpcServer);
$conn = new HyperfJsonRpc([
$conn = new JsonRpc([
'host' => $srv['host'],
'port' => $srv['port']
'port' => $srv['port'],
'mode' => JsonRpc::MODE_FRAME
]);
if (!$conn->connect()) {
......
......@@ -10,9 +10,24 @@ namespace internalApi\base;
use RuntimeException;
class HyperfJsonRpc
/**
* Hyperf JsonRpc 客户端
*/
class JsonRpc
{
/**
* 普通换行符文本协议
* 实现简单
*/
const MODE_EOF = 0;
/**
* 包头(包体长度)+包体的传输协议
* 效率高,使用前确认 frame_head_length 的值
*/
const MODE_FRAME = 1;
/**
* Holds a boolean indicating whether a connection to the server is
* currently established or not.
......@@ -41,7 +56,9 @@ class HyperfJsonRpc
'host' => '127.0.0.1',
'port' => 11300,
'timeout' => 1,
'logger' => null
'logger' => null,
'mode' => self::MODE_EOF,
'frame_head_length' => 4
];
$this->_config = $config + $defaults;
}
......@@ -136,7 +153,12 @@ class HyperfJsonRpc
throw new RuntimeException($message);
}
$data .= "\r\n";
if ($this->_config['mode'] == self::MODE_FRAME) {
$data = pack('N', strlen($data)).$data;
} else {
$data .= "\r\n";
}
return fwrite($this->_connection, $data, strlen($data));
}
......@@ -152,7 +174,24 @@ class HyperfJsonRpc
$message = 'No connection found while reading data from socket.';
throw new RuntimeException($message);
}
return stream_get_line($this->_connection, 16384, "\r\n");
if ($this->_config['mode'] == self::MODE_FRAME) {
$data = '';
$length = $current = 0;
while ($length == 0 || $current < $length) {
$data .= fread($this->_connection, $length == 0 ? 16384 : $length - $current);
$current = strlen($data);
if ($current < $this->_config['frame_head_length']) {
continue;
} elseif ($length == 0) {
$unpack = unpack('Nlen', substr($data, 0, $this->_config['frame_head_length']));
$length = $unpack['len'] + $this->_config['frame_head_length']; //package length
}
}
return substr($data, $this->_config['frame_head_length']);
} else {
return stream_get_line($this->_connection, 16384, "\r\n");
}
}
public function invoke($method, $params, $id=null)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment