go 简单的RPC服务与客户端通讯

// 服务器代码
package main


// rpc 服务
import (
	"net/rpc"
	"net"
	"log"
	"net/http"
)

type Name struct {
	MyName string
}

type Age struct {
	MyAge string
}

type My struct {
	Name string
	Age string
}
// 暴露api 接收一个Name指针结构 和一个指针字符串 返回一个错误信息
func (m *My) SetName (name *Name,s *string) error{
	*s = name.MyName+"Set-Name"
	return nil
}
// 暴露api
func (m *My) SetAge (age *Age,s *string) error{
	*s = age.MyAge
	return nil
}

func main() {
	arith:= new(My)
	rpc.Register(arith) // 注册
	rpc.HandleHTTP() // 初始化
	l,e:=net.Listen("tcp",":8080")

	if e!=nil {
		log.Fatal("sevice error.")
	}
	// 启动服务
	http.Serve(l,nil)
}

客户端代码

package main

// rpc 客户端
import (
	"net/rpc"
	"log"
	"fmt"
)
type MName struct {
	MyName string
}

func main()  {
	// 拨号链接服务
	client,err:=rpc.DialHTTP("tcp","127.0.0.1:8080")

	if err!=nil {
		log.Fatal("client not find")
	}
	name:=&MName{"lyl"} // 创建服务需要的结构参数
	var g string // 接收数据返回的类型
	err = client.Call("My.SetName",name,&g)

	fmt.Println(g) // 输出返回值

}

 

转载于:https://my.oschina.net/u/3529405/blog/1829873

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值