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

}

}

相关推荐
BingoGo1 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack1 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack2 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo2 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack3 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
花酒锄作田3 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言