grpc
实现rpc方法一net/rpc库
服务端代码
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/rpc"
"os"
)
type Arith struct {
}
type ArithRequest struct {
A int
B int
}
type ArithResponse struct {
Res int
}
func (*Arith) Add(req ArithRequest, res *ArithResponse) error {
res.Res = req.A + req.B
return nil
}
func main() {
rpc.Register(new(Arith))
rpc.HandleHTTP()
l, err := net.Listen("tcp", "127.0.0.1:8890")
if err != nil {
log.Fatalln("fatal error:", err)
}
fmt.Fprintf(os.Stdout, "%s", "start connection")
http.Serve(l, nil)
}
客户端代码
package main
import (
"fmt"
"log"
"net/rpc"
)
type ArithRequest struct {
A int
B int
}
type ArithResponse struct {
Res int
}
func main() {
c, err := rpc.DialHTTP("tcp", "127.0.0.1:8890")
if err != nil {
log.Fatalln("error:", err)
}
req := ArithRequest{9, 2}
var res ArithResponse
err2 := c.Call("Arith.Add", req, &res)
if err2 != nil {
log.Fatalln("error:", err2)
}
fmt.Printf("res.Res: %v\n", res.Res)
}
运行结果
实现rpc方法二jsonrpc库
此方式实现的RPC方法支持跨语言调用 服务端代码
package main
import (
"fmt"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"os"
)
type Arith struct {
}
type ArithRequest struct {
A int
B int
}
type ArithResponse struct {
Res int
}
func (*Arith) Add(req ArithRequest, res *ArithResponse) error {
res.Res = req.A + req.B
return nil
}
func main() {
rpc.Register(new(Arith))
l, err := net.Listen("tcp", "127.0.0.1:8890")
if err != nil {
log.Fatalln("fatal error:", err)
}
fmt.Fprintf(os.Stdout, "%s", "start connection\n")
for {
conn, err := l.Accept()
if err != nil {
continue
}
go func(conn net.Conn) {
fmt.Fprintf(os.Stdout, "%s", "new client in coming\n")
jsonrpc.ServeConn(conn)
}(conn)
}
}
go客户端代码
package main
import (
"fmt"
"log"
"net/rpc/jsonrpc"
)
type ArithRequest struct {
A int
B int
}
type ArithResponse struct {
Res int
}
func main() {
conn, err := jsonrpc.Dial("tcp", "127.0.0.1:8890")
if err != nil {
log.Fatalln("dailing error: ", err)
}
req := ArithRequest{9, 12}
var res ArithResponse
err = conn.Call("Arith.Add", req, &res)
if err != nil {
log.Fatalln("arith error: ", err)
}
fmt.Printf("res.Res: %v\n", res.Res)
}
php客户端代码
<?php
class JsonRPC{
private $conn;
function __construct($host, $port) {
$this->conn = fsockopen($host, $port, $errno, $errstr, 3);
if (!$this->conn) {
return false;
}
}
public function Call($method, $params) {
if ( !$this->conn ) {
return false;
}
$err = fwrite($this->conn, json_encode(
array(
'method' => $method,
'params' => array($params),
'id' => 1,
)
));
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);
}
}
$client = new JsonRPC("127.0.0.1", 8890);
$r = $client->Call("Arith.Add",array('A'=>1,'B'=>2));
var_dump($r);
运行结果
|