php-golang-rpc 简单的jsonrpc实践

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);
相关推荐
ANYOUZHEN1 天前
bugku shell
android
南宫码农1 天前
我的电视 - Android原生电视直播软件 完整使用教程
android·开发语言·windows·电视盒子
道亦无名1 天前
音频数据特征值提取 方法和步骤
android·音视频
Lancker1 天前
定制侠 一个国产纯血鸿蒙APP的诞生过程
android·华为·智能手机·鸿蒙·国产操作系统·纯血鸿蒙·华为鸿蒙
2601_949809591 天前
flutter_for_openharmony家庭相册app实战+通知设置实现
android·javascript·flutter
液态不合群1 天前
【面试题】MySQL 中 count(*)、count(1) 和 count(字段名) 有什么区别?
android·数据库·mysql
雪球Snowball1 天前
【Android关键流程】资源加载
android
2501_915918411 天前
常见 iOS 抓包工具的使用,从代理抓包、设备抓包到数据流抓包
android·ios·小程序·https·uni-app·iphone·webview
墨月白1 天前
[QT]QProcess的相关使用
android·开发语言·qt
enbug1 天前
编译安卓内核:以坚果R1、魔趣MK100(Android 10)系统为例
android·linux