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 天前
PHP 如何利用 Opcache 来实现保护源码
后端·php
BingoGo2 天前
2025 年 PHP 常见面试题整理以及对应答案和代码示例
后端·php
Bruce1233 天前
web专题之php代审(二)
php
侃侃_天下3 天前
最终的信号类
开发语言·c++·算法
BingoGo3 天前
PHP-FPM 深度调优指南 告别 502 错误,让你的 PHP 应用飞起来
后端·php
echoarts3 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix3 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题3 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说3 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔3 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机