Home>Article>Backend Development> PHP implements communication with go through JSON RPC (code attached)

PHP implements communication with go through JSON RPC (code attached)

藏色散人
藏色散人 forward
2023-01-13 10:16:40 3901browse

This article brings you relevant knowledge about php and golang. It mainly introduces how php communicates with go through JSON RPC. Let's take a look at it together. I hope it will be helpful to friends in need.

PHP implements communication with go through JSON RPC (code attached)

php communicates with golang through JSON RPC

This method solves the computationally intensive needs of PHP processing.

I don’t know why, it cannot be accessed across servers. If you know, please leave a message.

go service

package main import ( "fmt" "log" "net" "net/rpc" "net/rpc/jsonrpc" ) type Calc struct{} type Args struct { A float64 `json:"a"` B float64 `json:"b"` Op string `json:"op"` } type Reply struct { Msg string `json:"msg"` Data float64 `json:"data"` } // 第一个是参数是获取客户端传来的数据,第二个参数是返回的数据 func (c *Calc) Compute(args Args, reply *Reply) error { var ( msg string = "ok" ) switch args.Op { case "+": reply.Data = args.A + args.B case "-": reply.Data = args.A - args.B case "*": reply.Data = args.A * args.B case "/": if args.B == 0 { msg = "in divide op, B can't be zero" } else { reply.Data = args.A / args.B } default: msg = fmt.Sprintf("unsupported op:%s", args.Op) } reply.Msg = msg if reply.Msg == "ok" { return nil } return fmt.Errorf(msg) } // 启动server端 func main() { err := rpc.Register(new(Calc)) if err != nil { panic(err) } listener, err := net.Listen("tcp", "127.0.0.1:8181") if err != nil { panic(err) } for { conn, err := listener.Accept() if err != nil { log.Println(err) continue } go jsonrpc.ServeConn(conn) } }

php client

public function Call($method, $params) { $this->conn = fsockopen('127.0.0.1', 8181, $errno, $errstr, 3); if (!$this->conn) { return false; } $err = fwrite($this->conn, json_encode(array( 'method' => $method, 'params' => array($params), 'id' => 12345, ))."\n"); if ($err === false) return false; stream_set_timeout($this->conn, 0, 3000); $line = fgets($this->conn); if ($line === false) { return NULL; } return json_decode($line,true); } public function Test() { //访问结构体 Calc 下 Compute 方法 $res = $this->Call("Calc.Compute",array('A'=>1,'B'=>2,'Op'=>'+')); return $res; }

Return result

{ "id": 12345, "result": { "msg": "ok", "data": 3 }, "error": null }

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of PHP implements communication with go through JSON RPC (code attached). For more information, please follow other related articles on the PHP Chinese website!

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