Go语言内部rpc简单实例,实现python调用go的jsonrpc小实例

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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值