/*********************************** 函数描述:: 启动服务 ***********************************/ func (this *Server) StartServer() error { if len(this.Services) == 0 { return errors.New("No Registed Service.") } lis, err := net.Listen(this.Network, this.Address) if err != nil { return err } defer lis.Close() srv := rpc.NewServer() //注册服务 for key, value := range this.Services { if err := srv.RegisterName(key, value); err != nil { return err } } for { conn, err := lis.Accept() if err != nil { log.Fatalf("lis.Accept(): %v\n", err) } go srv.ServeCodec(protorpc.NewServerCodec(conn)) } }
// AcceptArithServiceClient accepts connections on the listener and serves requests // for each incoming connection. Accept blocks; the caller typically // invokes it in a go statement. func AcceptArithServiceClient(lis net.Listener, x ArithService) { srv := rpc.NewServer() if err := srv.RegisterName("ArithService", x); err != nil { log.Fatal(err) } for { conn, err := lis.Accept() if err != nil { log.Fatalf("lis.Accept(): %v\n", err) } go srv.ServeCodec(protorpc.NewServerCodec(conn)) } }
// ListenAndServeArithService listen announces on the local network address laddr // and serves the given ArithService implementation. func ListenAndServeArithService(network, addr string, x ArithService) error { lis, err := net.Listen(network, addr) if err != nil { return err } defer lis.Close() srv := rpc.NewServer() if err := srv.RegisterName("ArithService", x); err != nil { return err } for { conn, err := lis.Accept() if err != nil { log.Fatalf("lis.Accept(): %v\n", err) } go srv.ServeCodec(protorpc.NewServerCodec(conn)) } }
func main() { ln, err := net.Listen("tcp", "127.0.0.1:1234") if err != nil { log.Fatalln(err) } srv := rpc.NewServer() if err := service.RegisterArithService(srv, new(Arith)); err != nil { log.Fatalln(err) } if err := service.RegisterEchoService(srv, new(Echo)); err != nil { log.Fatalln(err) } for { conn, err := ln.Accept() if err != nil { log.Fatalln(err) } go srv.ServeCodec(protorpc.NewServerCodec(conn)) } panic("unreachable") }