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

How does laravel call golang program through rpc

藏色散人
Release: 2021-03-11 09:00:47
forward
2562 people have browsed it

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)
    }}
Copy after login

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));}
Copy after login

Return results

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

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template