PHP原生实现微服务RPC

 PHP      阅读(121)   2019-07-16 22:40:32 

/**
* 用户服务类
* Class User
*/
class User{
public function get_name($name = ''){
return $name;
}
}

/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/7/16
* Time: 21:22
*/
//原生实现php微服务rpc通信
$socket_server = stream_socket_server('tcp://0.0.0.0:9502',$errno,$errstr);
if (!$socket_server){
echo "异常代码".$errno.'异常信息'.$errstr;
exit;
}
while (1){
try{
$return_data = [];
$buff = @stream_socket_accept($socket_server);
//读取数据
$data = @fread($buff,2048);
$_json_data = json_decode($data,true);
$class = $_json_data['class'];
$file = $class.'.php';
if (!file_exists($file)){
continue;
}
require_once $file;
$method = $_json_data['method']; //客户端访问的方法
$user_obj = new $class();
if (isset($_json_data['param']) && !empty($_json_data['param'])){
$param = $_json_data['param'];
$server_data = $user_obj->$method($param);
}else{
$server_data = $user_obj->$method();
}
$return_data['code'] = 1;
$return_data['data'] = $server_data;
$return_data['msg'] = 'ok';
$return_data = json_encode($return_data);
//写入数据
@fwrite($buff,$return_data);
@fclose($buff); //关闭
}catch (\Exception $exception){
$err['code '] = $exception->getCode();
$err['data'] = '';
$err['msg'] = $exception->getMessage();
$err = json_encode($err);
@fwrite($buff,$exception);
@fclose($buff);
}
}
$client = stream_socket_client('tcp://119.23.15.2:9502',$errno,$errstr);
if (!$client){
echo "异常代码!".$errno.'异常信息'.$errstr;
EXIT;
}
$data['class'] = $_GET['c'];
$data['method'] = $_GET['m'];
$data['param'] = 7;
$_data = json_encode($data);
fwrite($client,$_data);
$server_data = fread($client,2048);
$result1 = json_decode($server_data,true);
fclose($client);
if ($result1['code'] ==1){
print_r($result1);
}


启动server.php文件,浏览器访问client.php .像访问本地函数一样访问


我要评论



展示评论