package main
import (
"errors"
"fmt"
"net/http"
"net/rpc"
)
func s_main() {
rpc.Register(new(Remote))
rpc.HandleHTTP()
http.ListenAndServe(":1789", nil)
}
func main() {
args := Test{"di", 24, []string{"basketball", "buitifulgirl"}}
client, err := rpc.DialHTTP("tcp", "127.0.0.1:1789")
if err != nil {
fmt.Println(err)
return
}
var b bool
err = client.Call("Remote.GetInfo", args, &b)
if err != nil {
fmt.Println(err)
}
var s string
err = client.Call("Remote.GetName", "WaCao", &s)
if err != nil {
fmt.Println(err)
}
fmt.Println(b, s)
}
type Remote int32
type Test struct {
Name string
Age int
Hobby []string
}
func (x *Remote) GetName(args string, result *string) error {
if args != "" {
*result = args
return nil
}
return errors.New("Input Empty")
}
func (x *Remote) GetInfo(args Test, result *bool) error {
if len(args.Hobby) == 0 {
return errors.New("Hobby Is Empty")
}
fmt.Println(args)
*result = true
return nil
}
下面这个个实例是使用jsonrpc实现给其他的语言提供rpc调用:
maste.go
package main
import (
"errors"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
func main() {
lis, err := net.Listen("tcp", ":1789")
if err != nil {
return
}
defer lis.Close()
srv := rpc.NewServer()
if err := srv.RegisterName("Json", new(Json)); err != nil {
return
}
for {
conn, err := lis.Accept()
if err != nil {
log.Fatalf("lis.Accept(): %v\n", err)
continue
}
go srv.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}
type Json struct {
Name string `json:name`
Age int `json:age`
}
func (self *Json) Getname(args Json, result *Json) error {
if args.Name == "di" {
log.Println(args)
*result = Json{"Xichen", 24}
return nil
}
return errors.New("Input Name")
}
在这里使用python作为客户端来实现远程调用的:
import json
import socket
import itertools
import time
class RPCClient(object):
def __init__(self, addr, codec=json):
self._socket = socket.create_connection(addr)
self._id_iter = itertools.count()
self._codec = codec
def _message(self, name, *params):
return dict(id=self._id_iter.next(),
params=list(params),
method=name)
def call(self, name, *params):
req = self._message(name, *params)
id = req.get('id')
mesg = self._codec.dumps(req)
self._socket.sendall(mesg)
# This will actually have to loop if resp is bigger
resp = self._socket.recv(4096)
resp = self._codec.loads(resp)
if resp.get('id') != id:
raise Exception("expected id=%s, received id=%s: %s"
%(id, resp.get('id'), resp.get('error')))
if resp.get('error') is not None:
raise Exception(resp.get('error'))
return resp.get('result')
def close(self):
self._socket.close()
if __name__ == '__main__':
rpc = RPCClient(("127.0.0.1", 1789))
mv = dict(name="di",age=24)
print rpc.call("Json.Getname", mv)