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