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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!