GO RPC 远程过程调用

/rpcintf/intf.go

package rpcintf

import "net/rpc"

// 代码可以自动生成,通过protoc,插件可以自己写

// Server
// ServerName
const HelloServiceName = "path/to/pkg.HelloService"

// Function list
type HelloServiceInterface = interface {
	Hello(request string, reply *string) error
}

// Register Function
func RegisterHelloService(svc HelloServiceInterface) error {
	return rpc.RegisterName(HelloServiceName, svc)
}

// Client
type HelloServiceClient struct {
	*rpc.Client
}

var _ HelloServiceInterface = (*HelloServiceClient)(nil)

func (p *HelloServiceClient) Hello(request string, reply *string) error {
	return p.Client.Call(HelloServiceName+".Hello", request, reply)
}

func DialHelloService(network, address string) (*HelloServiceClient, error) {
	c, err := rpc.Dial(network, address)
	if nil != err {
		return nil, err
	}
	return &HelloServiceClient{Client: c}, nil
}

server/server.go

package main

import (
	"log"
	"net"
	"net/rpc"

	"../rpcintf"
)

type HelloService struct{}

func (p *HelloService) Hello(request string, reply *string) error {
	*reply = "hello: " + request
	return nil
}

func main() {
	rpcintf.RegisterHelloService(new(HelloService))

	listener, err := net.Listen("tcp", ":1234")
	if nil != err {
		log.Fatal("ListenTCP error: ", err)
	}

	for {
		conn, err := listener.Accept()
		if nil != err {
			log.Fatal("Accept error: ", err)
		}
		go rpc.ServeConn(conn)
	}
}

client/client.go

package main

import (
	"fmt"
	"log"

	"../rpcintf"
)

func main() {

	client, err := rpcintf.DialHelloService("tcp", "localhost:1234")
	if nil != err {
		log.Fatal("dialing: ", err)
	}

	var reply string
	err = client.Hello("Hello", &reply)
	if nil != err {
		log.Fatal(err)
	}

	fmt.Println("recv: ", reply)
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值