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封装:文章来源:https://www.toymoban.com/news/detail-620310.html
PHP 端的就送 rpc 调用:rpc_client.php文章来源地址https://www.toymoban.com/news/detail-620310.html
<?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);
到了这里,关于php-golang-rpc 简单的jsonrpc实践的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!