-
Notifications
You must be signed in to change notification settings - Fork 85
/
server.go
123 lines (95 loc) · 2 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//
// Copyright (c) 2018- yutopp (yutopp@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//
package rtmp
import (
"io"
"net"
"sync"
"github.com/pkg/errors"
)
type Server struct {
config *ServerConfig
listener net.Listener
mu sync.Mutex
doneCh chan struct{}
}
type ServerConfig struct {
OnConnect func(net.Conn) (io.ReadWriteCloser, *ConnConfig)
}
func NewServer(config *ServerConfig) *Server {
return &Server{
config: config,
}
}
func (srv *Server) Serve(l net.Listener) error {
if err := srv.registerListener(l); err != nil {
return errors.Wrap(err, "Already served")
}
defer l.Close()
for {
rwc, err := l.Accept()
if err != nil {
select {
case <-srv.getDoneCh(): // closed
return ErrClosed
default: // do nothing
}
continue
}
go srv.handleConn(rwc)
}
}
func (srv *Server) Close() error {
srv.mu.Lock()
defer srv.mu.Unlock()
doneCh := srv.getDoneChLocked()
select {
case <-doneCh: // already closed
return nil
default:
close(doneCh)
}
if srv.listener == nil {
return nil
}
return srv.listener.Close()
}
func (srv *Server) registerListener(l net.Listener) error {
srv.mu.Lock()
defer srv.mu.Unlock()
if srv.listener != nil {
return errors.New("Listener is already registered")
}
srv.listener = l
return nil
}
func (srv *Server) getDoneCh() chan struct{} {
srv.mu.Lock()
defer srv.mu.Unlock()
return srv.getDoneChLocked()
}
func (srv *Server) getDoneChLocked() chan struct{} {
if srv.doneCh == nil {
srv.doneCh = make(chan struct{})
}
return srv.doneCh
}
func (srv *Server) handleConn(conn net.Conn) {
userConn, connConfig := srv.config.OnConnect(conn)
c := newConn(userConn, connConfig)
sc := &serverConn{
conn: c,
}
defer sc.Close()
if err := sc.Serve(); err != nil {
if err == io.EOF {
c.logger.Infof("Server closed")
return
}
c.logger.Errorf("Server closed by error: Err = %+v", err)
}
}