laravel 通过 rpc 调用 golang 程序
Golang 服务端
package main
import (
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type Goods struct{}
//方法(必须是公有方法,且必须是两个参数)
func (g *Goods) GetName(args string , res *string) error {
*res = "args=" + args
return nil
}
func main() {
//注册rpc服务,并自定义服务名
err := rpc.RegisterName("Goods",new(Goods))
if err != nil {
panic(err.Error())
}
//监听端口,如果监听所有客户端则去掉ip
listen, err := net.Listen("tcp", "127.0.0.1:7081")
if err != nil {
panic(err.Error())
}
fmt.Println("启动服务...")
for {
conn, err := listen.Accept() // 接收客户端连接请求
if err != nil {
continue
}
go jsonrpc.ServeConn(conn)
}
}
PHP 客户端
public function test(){
$host = '127.0.0.1';
$port = '7081';
$conn = fsockopen($host, $port, $errno, $errstr, 3);
if (!$conn) {
dd('链接失败');
}
$method = 'Goods.GetName';
$params = "我是字符串参数";
$err = fwrite($conn, json_encode(array(
'method' => $method,
'params' => [$params],
'id' => 0,
))."\n");
if ($err === false){
dd('写入数据失败');
}
stream_set_timeout($conn, 0, 30000);//超时配置
$line = fgets($conn);
if ($line === false) {
dd('获取响应数据失败');
}
dd(json_decode($line,true));
}
返回结果
array:3 [
"id" => 0
"result" => "args=我是字符串参数"
"error" => null
]
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: