golang 代码:
package main
import (
"fmt"
"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) {
fmt.Println("new client")
jsonrpc.ServeConn(conn)
}(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('1.0');
$request = $connection->sendRequest('App.Hi', array(['name'=>'ceshi222']));
dd($request->result);
}
}
错误排查:
on: cannot unmarshal string into Go value of type [1]interface {}
使用jsonrpc的时候报以上两个错误,一个是因为
{
"id": 1000,
"method": "Arith.Divide",
"params": "[{A:9,B:2}]"
}
一个是因为
{
"id": 1000,
"method": "Arith.Divide",
"params": {
"A": 9,
"B": 2
}
}
正确的应该是
php端需要多加一层数组:
{
"id": 1000,
"method": "Arith.Divide",
"params": [{
"A": 9,
"B": 2
}]
}