基于http

This commit is contained in:
suguo.yao 2021-09-18 16:56:04 +08:00
commit a94bef37f1
4 changed files with 74 additions and 0 deletions

34
client/main.go Normal file
View File

@ -0,0 +1,34 @@
package main
import (
"fmt"
"log"
"net/rpc"
"os"
"myschools.me/suguo/rpc-sample/server"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "server")
os.Exit(1)
}
serverAddress := os.Args[1]
client, err := rpc.DialHTTP("tcp", serverAddress+":1234")
if err != nil {
log.Fatal("dialing : ", err)
}
//Synchronous call
args := server.HelloRequest{
Name: "tom",
}
var reply server.HelloResponse
err = client.Call("Hello.Say", args, &reply)
if err != nil {
log.Fatal("hello error : ", err)
}
fmt.Printf("Result: %s \n", reply.Reply)
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module myschools.me/suguo/rpc-sample
go 1.17

18
main.go Normal file
View File

@ -0,0 +1,18 @@
package main
import (
"fmt"
"net/http"
"net/rpc"
"myschools.me/suguo/rpc-sample/server"
)
func main() {
rpc.Register(&server.Hello{})
rpc.HandleHTTP()
err := http.ListenAndServe(":1234", nil)
if err != nil {
fmt.Println(err.Error())
}
}

19
server/hello-server.go Normal file
View File

@ -0,0 +1,19 @@
package server
type HelloRequest struct {
Name string
}
type HelloResponse struct {
Reply string
}
type Hello struct {
}
func (*Hello) Say(req HelloRequest, reply *HelloResponse) error {
*reply = HelloResponse{
Reply: "hello " + req.Name,
}
return nil
}