From f654dc2b6e807c44ce3d445f3276cff44723aa31 Mon Sep 17 00:00:00 2001 From: chai2010 Date: Thu, 28 Jun 2018 15:41:09 +0800 Subject: [PATCH] =?UTF-8?q?ch4-01:=20=E5=AE=8C=E5=96=84=E4=BE=8B=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hello-service-v3/client/main.go | 36 +++++++++++++++++ .../hello-service-v3/server/main.go | 40 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 examples/ch4-01-rpc-inro/hello-service-v3/client/main.go create mode 100644 examples/ch4-01-rpc-inro/hello-service-v3/server/main.go diff --git a/examples/ch4-01-rpc-inro/hello-service-v3/client/main.go b/examples/ch4-01-rpc-inro/hello-service-v3/client/main.go new file mode 100644 index 0000000..a845ae5 --- /dev/null +++ b/examples/ch4-01-rpc-inro/hello-service-v3/client/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "log" + "net" + "net/rpc" + "net/rpc/jsonrpc" +) + +var flagAddr = flag.String("addr", "localhost:1234", "server address") + +func main() { + flag.Parse() + + // nc localhost 1234 + // {"method":"HelloService.Hello","params":["hello"],"id":0} + // echo -e '{"method":"HelloService.Hello","params":["hello2222"],"id":3}' | nc localhost 1234 + // echo -e '{"method":"HelloService.Hello","params":["hello2222"],"id":3}{"method":"HelloService.Hello","params":["hello33"],"id":4}' | nc localhost 1234 + + conn, err := net.Dial("tcp", *flagAddr) + if err != nil { + log.Fatal("net.Dial:", err) + } + + client := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn)) + + var reply string + err = client.Call("HelloService.Hello", "hello", &reply) + if err != nil { + log.Fatal(err) + } + + fmt.Println(reply) +} diff --git a/examples/ch4-01-rpc-inro/hello-service-v3/server/main.go b/examples/ch4-01-rpc-inro/hello-service-v3/server/main.go new file mode 100644 index 0000000..d93debc --- /dev/null +++ b/examples/ch4-01-rpc-inro/hello-service-v3/server/main.go @@ -0,0 +1,40 @@ +package main + +import ( + "flag" + "fmt" + "log" + "net" + "net/rpc" + "net/rpc/jsonrpc" +) + +type HelloService struct{} + +func (p *HelloService) Hello(request string, reply *string) error { + *reply = "hello:" + request + return nil +} + +var flagPort = flag.Int("port", 1234, "listen port") + +func main() { + flag.Parse() + + rpc.RegisterName("HelloService", new(HelloService)) + + // nc -l 2399 + listener, err := net.Listen("tcp", fmt.Sprintf(":%d", *flagPort)) + if err != nil { + log.Fatal("ListenTCP error:", err) + } + + for { + conn, err := listener.Accept() + if err != nil { + log.Fatal("Accept error:", err) + } + + go rpc.ServeCodec(jsonrpc.NewServerCodec(conn)) + } +}