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

}

}

相关推荐
郑州光合科技余经理1 天前
从零到一:构建UberEats式海外版外卖系统
java·开发语言·前端·javascript·架构·uni-app·php
Ralph_Y1 天前
const_cast正确用法与风险规避
开发语言·c++
codeejun1 天前
每日一Go-25、Go语言进阶:深入并发模式1
开发语言·后端·golang
xiaoliuliu123451 天前
treeNMS-1.7.5部署步骤详解(附Java环境准备与数据库配置)
java·开发语言·数据库
sycmancia1 天前
C++——友元、函数重载、操作符重载
开发语言·c++
m0_738120721 天前
应急响应——Solar月赛emergency靶场溯源过程(内含靶机下载以及流量分析)
java·开发语言·网络·redis·web安全·系统安全
Java面试题总结1 天前
Tube - Video Reactions
开发语言·前端·javascript
kylezhao20191 天前
C#中 Invoke、begininvoke、InvokeRequired的详细讲解和三者之间的区别
开发语言·c#
bubiyoushang8881 天前
基于遗传算法的LQR控制器最优设计算法
开发语言·算法·matlab
北京_小杰子1 天前
Windows10本地安装SQLserver数据库连接的过程
数据库·windows·sqlserver·php