php-golang-jsonrpc2.0 rpc-codec/jsonrpc2和tivoka/tivoka实践

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);

}

}

相关推荐
JaguarJack39 分钟前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo42 分钟前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack16 小时前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay2 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954482 天前
CTF 伪协议
php
BingoGo4 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack4 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo5 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack5 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack6 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端