Golang RPC

Server.go
package main

import (
    "fmt"
    "net/rpc"
    "net"
    "log"
    "sync"
)

type Arg struct {
    Param1 string
}
type Request struct{
    Arg1 int
    Arg2 string
    Arg3 *Arg

}
type Response struct {
    Arg1 int
    Arg2 string
    Arg3 *Arg
}
type Arith int
var lock sync.Mutex
var count =0
func (t *Arith) Deal(args Request, reply *Response) error {
    lock.Lock()
    count+=1
    lock.Unlock()
    fmt.Println("Count : ",count)
    fmt.Println(args)
    reply.Arg2="t2"
    reply.Arg1=111
    //reply.Arg3=new(Arg)
    reply.Arg3=&Arg{"Response"}
    //reply.Arg3.Param1="Response"
    fmt.Println(reply)
    return nil
}
func main() {
    newServer := rpc.NewServer()
    newServer.RegisterName("RpcServer",new(Arith))
    l, e := net.Listen("tcp", "127.0.0.1:1234") // any available address
    if e != nil {
        log.Fatalf("net.Listen tcp :0: %v", e)
    }
    fmt.Println("Waiting.")
    newServer.Accept(l)
    newServer.HandleHTTP("/foo", "/bar")
}

client.go

package main

import (
    "net"
    "net/rpc"
    "fmt"
    "time"
)
type Arg struct {
    Param1 string
}
type Request struct{
    Arg1 int
    Arg2 string
    Arg3 *Arg

}
type Response struct {
    Arg1 int
    Arg2 string
    Arg3 *Arg
}
func main() {

    for i:=10;i>=0;i-- {
        go func() {
            address, err := net.ResolveTCPAddr("tcp", "127.0.0.1:1234")
            if err != nil {
                panic(err)
            }
            conn, err := net.DialTCP("tcp", nil, address)
            defer conn.Close()

            client := rpc.NewClient(conn)
            defer client.Close()

            r := new(Request)
            r.Arg1 = i
            r.Arg2 = "2"
            r.Arg3 = &Arg{"Req1"}
            fmt.Println(r)
            res := new(Response)
            res.Arg3 = new(Arg)
            err = client.Call("RpcServer.Deal", r, &res)
            fmt.Println(res)
            fmt.Println(res.Arg3.Param1)
            if err != nil {
                fmt.Println(err)
            }
        }()
    }
    time.Sleep(10*time.Second)
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值