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)
}

客戶端代碼api

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) // 輸出返回值

}
相關文章
相關標籤/搜索