golang代码:
package main
import (
"context"
"net"
"net/rpc"
"github.com/powerman/rpc-codec/jsonrpc2"
)
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
}
type exampleContextKey string
var RemoteAddrContextKey exampleContextKey = "RemoteAddr"
func main() {
rpc.Register(&App{})
//Server provide a TCP transport.
lnTCP, err := net.Listen("tcp", "127.0.0.1:6001")
if err != nil {
panic(err)
}
defer lnTCP.Close()
for {
conn, err := lnTCP.Accept()
if err != nil {
return
}
ctx := context.WithValue(context.Background(), RemoteAddrContextKey, conn.RemoteAddr())
go jsonrpc2.ServeConnContext(ctx, conn)
}
}
/******************************************************/
php代码:
composer require tivoka/tivoka
<?php
namespace app\index\controller;
use app\BaseController;
use think\facade\View;
use Tivoka\Client;
class Index extends BaseController
{
public function index()
{
//tcp
$connection = Client::connect(array('host' => '127.0.0.1', 'port' => 6001));
$connection->useSpec('2.0');
$request = $connection->sendRequest('App.Hi', ['name'=>'ceshi222']);
dd($request->result);
}
}
文章来源:https://www.toymoban.com/news/detail-611818.html
文章来源地址https://www.toymoban.com/news/detail-611818.html
到了这里,关于php-golang-jsonrpc2.0 rpc-codec/jsonrpc2和tivoka/tivoka实践的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!