原生PHP实现RPC(上)

原生PHP实现RPC(上)

使用到的函数如下:

  • stream_socket_server
  • stream_socket_accept
  • Fread
  • Fwrite
  • fclose

创建服务器端:server.php

<?php

$stock_server = stream_socket_server("tcp://127.0.0.1:8887", $errno, $errstr);
if (!$stock_server) {
    echo '异常代码:' . $errno . ',异常信息' . $errstr;
    exit;
}

while (1) {
    try {
        $return_data = [];
        $buff = @stream_socket_accept($stock_server);
        $data = @fread($buff, 2048);
        $_json_data = json_decode($data, true);
        $class = $_json_data['class']; //客户端访问的类
        $file = $class . '.php';
        if (!file_exists($file)) {
            throw new Exception('文件不存在', '-1');
        }
        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 $e) {
        $err['code'] = $e->getCode();
        $err['data'] = '';
        $err['msg'] = $e->getMessage();
        $err = json_encode($err);
        @fwrite($buff, $err);
        @fclose($buff);
    }
}

创建用户服务类 user.php

<?php
//用户服务类
class user{
    public function get_name($age){
        return 'age is '.$age;
    }
    
    public function sum_data($int){
        return $int + 3;
    }
}

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注