您的位置 首页 php

laravel怎么通过rpc调用golang程序

下面由laravel教程栏目给大家介绍laravel怎么通过rpc调用golang程序 ,希望对需要的朋友有所帮助!

Golang 服务端

package mainimport (    "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]

推荐:最新的五个Laravel视频教程

文章来源:智云一二三科技

文章标题:laravel怎么通过rpc调用golang程序

文章地址:https://www.zhihuclub.com/25411.shtml

关于作者: 智云科技

热门文章

网站地图