php-golang-rpc 简单的jsonrpc实践

该文展示了如何使用Golang建立一个RPC服务器,处理JSONRPC请求,以及在PHP端如何封装一个RPC客户端进行调用。Golang服务器监听TCP端口,接收并响应PHP客户端的请求,PHP通过fsockopen函数连接到服务器并发送JSON编码的请求,获取响应并解码。
摘要由CSDN通过智能技术生成

golang代码:

package main

import (

    "net"

    "net/rpc"

    "net/rpc/jsonrpc"

)

type App struct{}

type Res struct {

    Code int    `json:"code"`

    Msg  string `json:"msg"`

    Data any    `json:"data"`

}

func (*App) Hi(mp map[string]any, res *Res) error {

    res.Code = 200

    res.Msg = "成功"

    var rmp = make(map[string]any, 0)

    if v, ok := mp["name"].(string); ok {

        rmp["name"] = "my name is " + v

    } else {

        rmp["name"] = "my name is unknown"

    }

    res.Data = rmp

    return nil

}

func main() {

    ln, err := net.Listen("tcp", ":6001")

    if err != nil {

        panic(err)

    }

    rpc.Register(new(App))

    for {

        conn, err := ln.Accept()

        if err != nil {

            continue

        }

        go func(conn net.Conn) {

            jsonrpc.ServeConn(conn)

        }(conn)

    }

}

/**************************************************************/

php代码:

public function index()
    {
        //访问结构体 Calc 下 Compute 方法
        $res = $this->Call("App.Hi",['name'=>'ceshi222']);
        dd($res);

     }

public function Call($method, $params) {
        
        $conn = fsockopen('127.0.0.1', 6001, $errno, $errstr, 3);
        if (!$conn) {
            return false;
        }
        
        $err = fwrite($conn, json_encode(array(
            'method' => $method,
            'params' => array($params),
            'id'     => time(),
        ))."\n");
        if ($err === false){
            return false;
        }
        
        stream_set_timeout($conn, 0, 3000);
        $line = fgets($conn);
        if ($line === false) {
            return NULL;
        }
        return json_decode($line,true);
    }

/***********************************************/

php封装:

PHP 端的就送 rpc 调用:rpc_client.php

<?php

class JsonRPC {
    private $conn;
    function __construct($host, $port) {
        $this->conn = fsockopen($host, $port, $errno, $errstr, 3);
        if (!$this->conn) {
            return false;
        }
    }
    public function Call($method, $params) {
        if (!$this->conn) {
            return false;
        }
        $err = fwrite($this->conn, json_encode(array(
                    'method' => $method,
                    'params' => array($params),
                    'id' => 0,
                )) . "\n");

        if ($err === false){
            return false;
        }
        stream_set_timeout($this->conn, 0, 3000);
        $line = fgets($this->conn);
        if ($line === false) {
            return NULL;
        }
        return json_decode($line, true);
    }
}
$client = new JsonRPC("127.0.0.1", 30002);
$r = $client->Call("ServiceCompute.Add", array('X' => 30, 'Y' => 40));
var_dump($r);
JsonRPC 2.0 Client and Server ============================= 轻量级 Json-RPC 2.0 客户端和服务端的php扩展,基于 multi_curl epoll的并发客户端,依据[jsonrpc](http://www.jsonrpc.org/)协议规范。 服务端: $server = new Jsonrpc_Server(); // style one function variable $add1 = function($a, $b){     return $a   $b; }; $server->register('addition1', $add1); // style two function string function add2($a, $b){   return $a   $b; } $server->register('addition2', 'add2'); // style three function closure $server->register('addition3', function ($a, $b) {     return $a   $b; }); //style four class method string class A  {   static public function add($a, $b)   {     return $a   $b;   } } $server->register('addition4', 'A::add'); echo $server->execute(); //output >>> //{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}} 客户端: $client = new Jsonrpc_Client(1); $client->call('http://localhost/server.php', 'addition1', array(3,5)); $client->call('http://localhost/server.php', 'addition2', array(10,20)); $client->call('http://localhost/server.php', 'addition3', array(2,8)); $client->call('http://localhost/server.php', 'addition4', array(6,15)); /* ... */ $result = $client->execute(); var_dump($result); //output >>> /* array(2) {   [0]=>   array(3) {     ["jsonrpc"]=>     string(3) "2.0"     ["id"]=>     int(110507766)     ["result"]=>     int(8)   }   [1]=>   array(3) {     ["jsonrpc"]=>     string(3) "2.0"     ["id"]=>     int(1559316299)     ["result"]=>     int(30)   }   ... } */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅坞茶坊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值