-
Notifications
You must be signed in to change notification settings - Fork 157
/
server.go
54 lines (45 loc) · 1.19 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2022 <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tinyrpc
import (
"log"
"net"
"net/rpc"
"github.com/zehuamama/tinyrpc/codec"
"github.com/zehuamama/tinyrpc/serializer"
)
// Server rpc server based on net/rpc implementation
type Server struct {
*rpc.Server
serializer.Serializer
}
// NewServer Create a new rpc server
func NewServer(opts ...Option) *Server {
options := options{
serializer: serializer.Proto,
}
for _, option := range opts {
option(&options)
}
return &Server{&rpc.Server{}, options.serializer}
}
// Register register rpc function
func (s *Server) Register(rcvr interface{}) error {
return s.Server.Register(rcvr)
}
// RegisterName register the rpc function with the specified name
func (s *Server) RegisterName(name string, rcvr interface{}) error {
return s.Server.RegisterName(name, rcvr)
}
// Serve start service
func (s *Server) Serve(lis net.Listener) {
log.Printf("tinyrpc started on: %s", lis.Addr().String())
for {
conn, err := lis.Accept()
if err != nil {
continue
}
go s.Server.ServeCodec(codec.NewServerCodec(conn, s.Serializer))
}
}