Swoole\Protocol\RPCServer::encode PHP Method

encode() static public method

打包数据
static public encode ( $data, $type = self::DECODE_PHP, $uid, $serid ) : string
$data
$type
$uid
$serid
return string
    static function encode($data, $type = self::DECODE_PHP, $uid = 0, $serid = 0)
    {
        //启用压缩
        if ($type & self::DECODE_GZIP) {
            $_type = $type & ~self::DECODE_GZIP;
            $gzip_compress = true;
        } else {
            $gzip_compress = false;
            $_type = $type;
        }
        switch ($_type) {
            case self::DECODE_JSON:
                $body = json_encode($data);
                break;
            case self::DECODE_PHP:
            default:
                $body = serialize($data);
                break;
        }
        if ($gzip_compress) {
            $body = gzencode($body);
        }
        return pack(RPCServer::HEADER_PACK, strlen($body), $type, $uid, $serid) . $body;
    }

Usage Example

Beispiel #1
0
 /**
  * 发送请求
  * @param $send
  * @param SOA_result $retObj
  * @return bool
  */
 protected function request($send, $retObj)
 {
     $retObj->send = $send;
     $this->beforeRequest($retObj);
     $retObj->index = $this->requestIndex++;
     connect_to_server:
     if ($this->connectToServer($retObj) === false) {
         $retObj->code = SOA_Result::ERR_CONNECT;
         return false;
     }
     //请求串号
     $retObj->requestId = self::getRequestId();
     //打包格式
     $encodeType = $this->encode_json ? RPCServer::DECODE_JSON : RPCServer::DECODE_PHP;
     if ($this->encode_gzip) {
         $encodeType |= RPCServer::DECODE_GZIP;
     }
     //发送失败了
     if ($retObj->socket->send(RPCServer::encode($retObj->send, $encodeType, 0, $retObj->requestId)) === false) {
         //连接被重置了,重现连接到服务器
         if ($this->haveSwoole and $retObj->socket->errCode == 104) {
             goto connect_to_server;
         }
         $retObj->code = SOA_Result::ERR_SEND;
         unset($retObj->socket);
         return false;
     }
     $retObj->code = SOA_Result::ERR_RECV;
     //加入wait_list
     $this->waitList[$retObj->id] = $retObj;
     return true;
 }