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 mapstringany, res *Res) error {

res.Code = 200

res.Msg = "成功"

var rmp = make(mapstringany, 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);

}

}

相关推荐
哥不想学算法2 小时前
【C++】字符串字面量拼接
开发语言·c++
gugucoding4 小时前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
Brookty4 小时前
【JavaEE】线程安全(一).4:写块串行保安全、CAS
java·开发语言·java-ee·多线程·线程安全
F20226974865 小时前
西门子 PLC 与 C# 通信
开发语言·c#
gugucoding5 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
万联WANFLOW6 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php
阿里嘎多学长6 小时前
2026-07-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
cookies_s_s7 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
盐焗鹌鹑蛋9 小时前
【C++】继承
开发语言·c++