1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 12:32:21 +00:00

ch4-01: 完善例子

This commit is contained in:
chai2010 2018-06-28 08:10:32 +08:00
parent 0c05e7c7a6
commit 229279a8d9
4 changed files with 99 additions and 3 deletions

View File

@ -78,7 +78,7 @@ type HelloServiceInterface = interface {
}
func RegisterHelloService(svc HelloServiceInterface) error {
rpc.RegisterName(HelloServiceName, svc)
return rpc.RegisterName(HelloServiceName, svc)
}
```
@ -117,11 +117,11 @@ func DialHelloService(network, address string) (*HelloServiceClient, error) {
if err != nil {
return nil, err
}
return &HelloServiceClient{Client: c}
return &HelloServiceClient{Client: c}, nil
}
func (p *HelloServiceClient) Hello(request string, reply *string) error {
return client.Call(HelloServiceName+".Hello", request, reply)
return p.Client.Call(HelloServiceName+".Hello", request, reply)
}
```

View File

@ -0,0 +1,31 @@
package api
import "net/rpc"
const HelloServiceName = "path/to/pkg.HelloService"
type HelloServiceInterface = interface {
Hello(request string, reply *string) error
}
func RegisterHelloService(svc HelloServiceInterface) error {
return rpc.RegisterName(HelloServiceName, svc)
}
type HelloServiceClient struct {
*rpc.Client
}
var _ HelloServiceInterface = (*HelloServiceClient)(nil)
func DialHelloService(network, address string) (*HelloServiceClient, error) {
c, err := rpc.Dial(network, address)
if err != nil {
return nil, err
}
return &HelloServiceClient{Client: c}, nil
}
func (p *HelloServiceClient) Hello(request string, reply *string) error {
return p.Client.Call(HelloServiceName+".Hello", request, reply)
}

View File

@ -0,0 +1,31 @@
package main
import (
"fmt"
"log"
"github.com/chai2010/advanced-go-programming-book/examples/ch4-01-rpc-inro/hello-service-v2/api"
)
type HelloService struct{}
func (p *HelloService) Hello(request string, reply *string) error {
*reply = "hello:" + request
return nil
}
func main() {
client, err := api.DialHelloService("tcp", "localhost:1234")
if err != nil {
log.Fatal("dialing:", err)
}
var reply string
err = client.Hello("hello", &reply)
if err != nil {
log.Fatal(err)
}
fmt.Println(reply)
}

View File

@ -0,0 +1,34 @@
package main
import (
"log"
"net"
"net/rpc"
"github.com/chai2010/advanced-go-programming-book/examples/ch4-01-rpc-inro/hello-service-v2/api"
)
type HelloService struct{}
func (p *HelloService) Hello(request string, reply *string) error {
*reply = "hello:" + request
return nil
}
func main() {
api.RegisterHelloService(new(HelloService))
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal("ListenTCP error:", err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal("Accept error:", err)
}
go rpc.ServeConn(conn)
}
}