golang -- rpc

前端之家收集整理的这篇文章主要介绍了golang -- rpc前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

内置的gob

rpcserver

packagemain

import(
"errors"
"fmt"
"net"
"net/rpc"
"os"
)

typeArgsstruct{
A,Bint
}

typeQuotientstruct{
Quo,Remint
}

typeArithint

func(t*Arith)Multiply(args*Args,reply*int)error{
*reply=args.A*args.B
returnnil
}

func(t*Arith)Divide(args*Args,quo*Quotient)error{
ifargs.B==0{
returnerrors.New("dividebyzero")
}
quo.Quo=args.A/args.B
quo.Rem=args.A%args.B
returnnil
}

funcmain(){
arith:=new(Arith)
rpc.Register(arith)
tcpAddr,err:=net.ResolveTCPAddr("tcp",":1234")
checkError(err)
listener,err:=net.ListenTCP("tcp",tcpAddr)
checkError(err)
/*
rpc.Accept(listener)
*/
for{
conn,err:=listener.Accept()
iferr!=nil{
continue
}
rpc.ServeConn(conn)
}
}

funccheckError(errerror){
iferr!=nil{
fmt.Println("Fatalerror",err.Error())
os.Exit(1)
}
}

rpcclient

packagemain

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

typeArgsstruct{
A,Remint
}

funcmain(){
iflen(os.Args)!=2{
fmt.Println("Usage:",os.Args[0],"server:port")
os.Exit(1)
}
service:=os.Args[1]
client,err:=rpc.Dial("tcp",service)
iferr!=nil{
log.Fatal("dialing:",err)
}
//Synchronouscall
args:=Args{17,8}
varreplyint
err=client.Call("Arith.Multiply",args,&reply)
iferr!=nil{
log.Fatal("aritherror:",err)
}
fmt.Printf("Arith:%d*%d=%d\n",args.A,args.B,reply)
varquotQuotient
err=client.Call("Arith.Divide",&quot)
iferr!=nil{
log.Fatal("aritherror:",err)
}
fmt.Printf("Arith:%d/%d=%dremainder%d\n",quot.Quo,quot.Rem)
}

测试

运行./server
运行./client127.0.0.1:1234
原文链接:https://www.f2er.com/go/191155.html

猜你在找的Go相关文章