mirror of
https://github.com/chai2010/advanced-go-programming-book.git
synced 2025-05-24 04:22:22 +00:00
ch4-01: 完善例子
This commit is contained in:
parent
229279a8d9
commit
f654dc2b6e
36
examples/ch4-01-rpc-inro/hello-service-v3/client/main.go
Normal file
36
examples/ch4-01-rpc-inro/hello-service-v3/client/main.go
Normal file
@ -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)
|
||||
}
|
40
examples/ch4-01-rpc-inro/hello-service-v3/server/main.go
Normal file
40
examples/ch4-01-rpc-inro/hello-service-v3/server/main.go
Normal file
@ -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))
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user