Created
January 9, 2022 15:00
-
-
Save AntiKnot/52ce7f128ea8f4349e183f5e63c7855e to your computer and use it in GitHub Desktop.
sample-go-rpc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "net/rpc" | |
| ) | |
| type DoubleArgs struct { | |
| Arg int | |
| } | |
| type DoubleReply struct { | |
| Res int | |
| } | |
| func main() { | |
| client, err := rpc.DialHTTP("tcp", "localhost:8081") | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| args := DoubleArgs{Arg: 1,} | |
| var reply *DoubleReply | |
| err = client.Call("MathUtil.Double", args, &reply) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| fmt.Println(reply.Res) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| run-server: | |
| go run server/server.go | |
| run-client: | |
| go run client/client.go |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "net" | |
| "net/http" | |
| "net/rpc" | |
| ) | |
| type MathUtil struct { | |
| } | |
| type DoubleArgs struct { | |
| Arg int | |
| } | |
| type DoubleReply struct { | |
| Res int | |
| } | |
| func (mu *MathUtil) Double(args DoubleArgs, reply *DoubleReply) error { | |
| reply.Res = 2 * args.Arg | |
| return nil | |
| } | |
| func main() { | |
| mathUtil := new(MathUtil) | |
| err := rpc.Register(mathUtil) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| rpc.HandleHTTP() | |
| listen, err := net.Listen("tcp", "localhost:8081") | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| http.Serve(listen, nil) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| . | |
| ├── Makefile | |
| ├── client | |
| │ └── client.go | |
| └── server | |
| └── server.go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment