php memcache在不应该的时候返回END


php memcache returning END when it shouldnt

我目前正在学习memcache。做一些简单的get/set查询,发现一个奇怪的行为

这就是我如何做set和get查询。

$memClient = new MemcacheClient('localhost', 11211);
$memClient->set('get1', 'value of get1');
$memClient->set('get2', 'value of get2');
$memClient->get('get1');
$memClient->get('get2');

这是我简单的MemcacheClient

Class MemcacheClient
{
    private $socket;
    private $reply;
    private $replies = [
        'OK' => true,
        'EXISTS' => false,
        'DELETED' => true,
        'STORED' => true,
        'NOT_STORED' => false,
        'NOT_FOUND' => false,
        'ERROR' => null,
        'CLIENT_ERROR' => null, 
        'SERVER_ERROR' => null
    ];
    public function __construct($host, $port)
    {
        $this->socket = stream_socket_client("$host:$port", $errno, $errstr);
        if(!$this->socket) {
            throw new 'Exception("$errst ($errno)");
        }
    }
    public function get($key)
    {
        $reply = $this->query("get $key");
        return $reply;
    }
    public function set($key, $value, $exptime = 0, $flags = 0)
    {
        return $this->query(array("set $key $flags $exptime ".strlen($value), $value));
    }
    private function query($query)
    {
        $query = is_array($query) ? implode("'r'n", $query) : $query;
        fwrite($this->socket, $query."'r'n");
        return $this->parseLine();
    }
    private function parseLine()
    {
        $line = fgets($this->socket);
        print $line.'<br>';
        $this->reply = substr($line, 0, strlen($line) - 2);
        $words = explode(' ', $this->reply);
        $result = isset($this->replies[$words[0]]) ? $this->replies[$words[0]] : $words;
        if (is_null($result)) {
            throw new 'Exception($this->reply);
        }
        if ($result[0] == 'VALUE') {
            $value = fread($this->socket, $result[3] + 2);
            return $value;
        }
        return $result;
    }
}

首先得到'get1'键的查询响应是VALUE get1 0 13第二个get查询'get2'键的响应是END

如果我执行两次,第三个响应将返回该值,第四个响应将再次返回END。

知道为什么吗?

谢谢

看起来,根据memcached协议,检索请求命令直到收到END才完成,但我没有看到您的代码说明这一点。

我认为对于您的代码,您需要在getgets命令上保持调用fgets(),直到收到END,然后解析结果。