此方法为解决php处理计算密集型需求。

不知道为啥,不能跨服务器访问,有知道的请留言。

go 服务

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 客户端

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

返回结果

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