我在Zend框架3中有一个客户端rpc json和一个服务器。当客户端调用服务器时,我有错误:
“解码失败:语法错误” 因为解码的json无效:
“的 {” 方法 “:” foobar的 “ ”ID“ 为 ”1“} { ”结果“:99, ”ID“ 为 ”1“} ”
服务器:
public function wsAction() {
$server = new \Zend\Json\Server\Server();
// Indicate what functionality is available:
$server->setClass('\Application\Model\Calculator')
->setResponse(new JsonResponse())
->setReturnResponse();
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/json-rpc.php')->setEnvelope(\Zend\Json\Server\Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return $this->getResponse();
}
$jsonRpcResponse = $server->handle();
// Get the content-type
$contentType = 'application/json-rpc';
if (null !== ($smd = $jsonRpcResponse->getServiceMap())) {
// SMD is being returned; use alternate content type, if present
$contentType = $smd->getContentType() ?: $contentType;
}
return new TextResponse(
$jsonRpcResponse->toJson(),
200,
['Content-Type' => $contentType]
);
}
客户:
public function wsclientAction() {
$client = new \Zend\Json\Server\Client('http://localhost/bac/zf3/public/application/index/ws');
$response = $client->call('foobar');
print_r($response);
return $this->getResponse();
}
服务:
class Calculator
{
/**
*
* @return int
*/
public function foobar()
{
return 99;
}
}
非常感谢您的帮助
我更改了服务器并且它可以工作:
I changed the server and it works :public function endpointAction()
{
$server = new \Zend\Json\Server\Server();
$server
->setClass('\Application\Model\Calculator')
->setResponse(new \Zend\Json\Server\Response())
->setReturnResponse();
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/json-rpc.php')->setEnvelope(\Zend\Json\Server\Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return $this->getResponse();
}
/** @var JsonResponse $jsonRpcResponse */
$jsonRpcResponse = $server->handle();
/** @var \Zend\Http\Response $response */
$response = $this->getResponse();
// Do we have an empty response?
if (! $jsonRpcResponse->isError()
&& null === $jsonRpcResponse->getId()
) {
$response->setStatusCode(204);
return $response;
}
// Set the content-type
$contentType = 'application/json-rpc';
if (null !== ($smd = $jsonRpcResponse->getServiceMap())) {
$contentType = $smd->getContentType() ?: $contentType;
}
// Set the headers and content
$response->getHeaders()->addHeaderLine('Content-Type', $contentType);
$response->setContent($jsonRpcResponse->toJson());
return $response;
}