前言
原生rpc,就是go语言自带的rpc框架,及net/rpc.
原生rpc,就是go语言自带的rpc框架,及net/rpc
server端
package main
import (
"crypto/md5"
"encoding/hex"
"net"
"net/http"
"net/rpc"
)
type EncryptionUtil struct {
}
func (eu *EncryptionUtil) Encryption(req string, resp *string) error {
*resp = ToMd5(req)
return nil
}
func ToMd5(s string) string{
m := md5.New()
m.Write([]byte (s))
return hex.EncodeToString(m.Sum(nil))
}
func main() {
encryption := new(EncryptionUtil)
err := rpc.Register(encryption)
if err != nil {
panic(err.Error())
}
rpc.HandleHTTP()
listen, err := net.Listen("tcp", ":8081")
if err != nil {
panic(err.Error())
}
_ = http.Serve(listen, nil)
}
client端口
#client.go
package main
import (
"fmt"
"net/rpc"
)
func main() {
client, err := rpc.DialHTTP("tcp", "这里填写server端ip地址:8081")
if err != nil {
panic(err.Error())
}
req := "mclink"
var resp *string
err = client.Call("EncryptionUtil.Encryption", req, &resp)
if err!= nil {
panic(err.Error())
}
fmt.Println(*resp)
syncCall := client.Go("EncryptionUtil.Encryption", req, &resp, nil)
replayDone := <-syncCall.Done
fmt.Println(replayDone)
fmt.Println(*resp)
}