PHP调用Go语言jsonrpc服务

博客日记 zhangshun 3个月前 (09-23) 137次浏览 已收录 0个评论

GO 语言服务端代码:

package main

import (
   "log"
   "net"
   "net/rpc"
   "net/rpc/jsonrpc"
)

func main() {
   //注册 rpc
   rpc.Register(new(Demo))
   //监听 1010 端口
   listen,err := net.Listen("tcp",":1010")
   if err != nil{
      log.Fatal("net.listen err=",err)
   }

   for{
      //不断接受请求
      conn,err := listen.Accept()
      if err != nil{
         continue
      }
      //开一个协程处理
      go jsonrpc.ServeConn(conn)
   }
}

type Demo struct {
}

func (d *Demo) Add(str string, reply *string) error {
   *reply = "add " + str
   return nil
}

func (d *Demo) Hi(str string, reply *string) error{
   *reply = "hello " + str
   return nil
}

PHP 客户端代码:

class JsonRpc
{
    protected $conn = null;
    protected $config = [
        "host" => "127.0.0.1",
        "port" => "1010"
    ];

    public function __construct($host = "", $port = "")
    {
        if ($host) {
            $this->config['host'] = $host;
        }

        if ($port) {
            $this->config['port'] = $port;
        }

        $this->conn = fsockopen($this->config['host'], $this->config['port'], $errno, $errstr, 3);
    }

    //获取值
    public function getCall($method, $param)
    {
        $data = [
            'method' => $method,
            'params' => array($param),
            'id'     => 0,
        ];
        $err = fwrite($this->conn,json_encode($data)."\n");
        if($err===false){
            return false;
        }
        stream_set_timeout($this->conn, 0, 3000);
        $line = fgets($this->conn);
        if ($line === false) {
            return "";
        }
        return json_decode($line,true);
    }
}

$client = new JsonRpc();
echo "<pre>";
$r = $client->getCall("Demo.Hi","你好,世界!");
$r2 = $client->getCall("Demo.Add","哈哈哈");
var_dump($r);
var_dump($r2);
echo "<pre>";

章顺的个人博客, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明PHP 调用 Go 语言 jsonrpc 服务
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址