Home  >  Article  >  PHP Framework  >  How does laravel call golang program through rpc

How does laravel call golang program through rpc

藏色散人
藏色散人forward
2021-03-10 15:21:002513browse

The following tutorial column will introduce to you how laravel calls golang programs through rpc. I hope it will be helpful to friends in need! Golang server

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 client

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

Return results

array:3 [
  "id" => 0
  "result" => "args=我是字符串参数"
  "error" => null]

Recommended: The latest five Laravel video tutorials

The above is the detailed content of How does laravel call golang program through rpc. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete