docker-webman-jsonrpc/jsonrpc/Server.php
2023-10-19 15:12:20 +08:00

56 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace jsonrpc;
use Workerman\Connection\TcpConnection;
/**
* 在config/process中把这个类注册为服务
*
*
* @author Aaron Chen <qiang.c@wukezhenzhu.com>
*/
class Server
{
/**
* 在项目的app目录下创建jsonrpc目录它下面的类的静态方法可以被jsonrpc客户端调用
*/
static $service_space = "app\\jsonrpc";
public function onMessage(TcpConnection $connection, $data)
{
// 判断数据是否正确
if (empty($data['class']) || empty($data['method']) || !isset($data['param_array'])) {
// 发送数据给客户端,请求包错误
return $connection->send(array('code' => 400, 'msg' => 'bad request'));
}
// 获得要调用的类、方法、及参数
$class = self::$service_space . "\\{$data['class']}";
$method = $data['method'];
$param_array = $data['param_array'];
// 判断类对应文件是否载入
if (!class_exists($class)) {
if (!class_exists($class) || !method_exists($class, $method)) {
$code = 404;
$msg = "class $class or method $method not found";
// 发送数据给客户端 类不存在
return $connection->send(array('code' => $code, 'msg' => $msg, 'data' => null));
}
}
// 调用类的方法
try {
$ret = call_user_func_array(array($class, $method), $param_array);
// 发送数据给客户端调用成功data下标对应的元素即为调用结果
return $connection->send($ret);
}
// 有异常
catch (\Exception $e) {
// 发送数据给客户端,发生异常,调用失败
$code = $e->getCode() ? $e->getCode() : 500;
return $connection->send(array('code' => $code, 'msg' => $e->getMessage(), 'data' => $e));
}
}
}