原生PHP的RPC服务与ThinkPHP框架结合(上)

建立两个服务器A和服务器B,服务器A为线上外网,服务器B为本地服务器,服务器B调用服务器A

建立服务器A: 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;
    }
}

启动A服务器的server.php 命令:

php server.php

使用netstat -anp 命令查看端口和进程(前提是服务器端口开放)

上面结果代表服务器A启动成功。

在本地服务器B 新建文件client.php 代码如下:

<?php

/**
 * @Author: ysq
 * @Date:   2020-02-16 21:47:28
 * @Last Modified by:   ysq
 * @Last Modified time: 2020-02-16 21:51:52
 */



$client = stream_socket_client("tcp://47.106.172.191:8080", $errno,$errstr);
if(!$client){
    echo '异常代码:'.$errno.',异常信息:'.$errstr;exit;
}

$data['class'] = $_GET['c'];
$data['method'] = $_GET['m'];
$data['param'] = 190;
$_data = json_encode($data);
fwrite($client, $_data);

$server_data = fread($client, 2048);
$resutl = json_decode($server_data,true);
fclose($client);
if($resutl['code']==1){
    print_r($resutl);
}else{
    echo $resutl['msg'];
}

本地运行 http://local.rpc.com/client.php?c=user&m=sum_data.

Comments are closed.