forked from bluenviron/gortsplib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn-server.go
92 lines (77 loc) · 2.13 KB
/
conn-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
package gortsplib
import (
"bufio"
"net"
"time"
)
const (
serverReadBufferSize = 4096
serverWriteBufferSize = 4096
)
// ConnServerConf allows to configure a ConnServer.
type ConnServerConf struct {
// pre-existing TCP connection that will be wrapped
Conn net.Conn
// (optional) timeout for read requests.
// It defaults to 5 seconds
ReadTimeout time.Duration
// (optional) timeout for write requests.
// It defaults to 5 seconds
WriteTimeout time.Duration
}
// ConnServer is a server-side RTSP connection.
type ConnServer struct {
conf ConnServerConf
br *bufio.Reader
bw *bufio.Writer
}
// NewConnServer allocates a ConnClient.
func NewConnServer(conf ConnServerConf) *ConnServer {
if conf.ReadTimeout == time.Duration(0) {
conf.ReadTimeout = 5 * time.Second
}
if conf.WriteTimeout == time.Duration(0) {
conf.WriteTimeout = 5 * time.Second
}
return &ConnServer{
conf: conf,
br: bufio.NewReaderSize(conf.Conn, serverReadBufferSize),
bw: bufio.NewWriterSize(conf.Conn, serverWriteBufferSize),
}
}
// NetConn returns the underlying net.Conn.
func (s *ConnServer) NetConn() net.Conn {
return s.conf.Conn
}
// ReadRequest reads a Request.
func (s *ConnServer) ReadRequest() (*Request, error) {
s.conf.Conn.SetReadDeadline(time.Time{}) // disable deadline
return ReadRequest(s.br)
}
// ReadFrameOrRequest reads an InterleavedFrame or a Request.
func (s *ConnServer) ReadFrameOrRequest(frame *InterleavedFrame) (interface{}, error) {
s.conf.Conn.SetReadDeadline(time.Now().Add(s.conf.ReadTimeout))
b, err := s.br.ReadByte()
if err != nil {
return nil, err
}
s.br.UnreadByte()
if b == interleavedFrameMagicByte {
err := frame.Read(s.br)
if err != nil {
return nil, err
}
return frame, err
}
return ReadRequest(s.br)
}
// WriteResponse writes a Response.
func (s *ConnServer) WriteResponse(res *Response) error {
s.conf.Conn.SetWriteDeadline(time.Now().Add(s.conf.WriteTimeout))
return res.Write(s.bw)
}
// WriteFrame writes an InterleavedFrame.
func (s *ConnServer) WriteFrame(frame *InterleavedFrame) error {
s.conf.Conn.SetWriteDeadline(time.Now().Add(s.conf.WriteTimeout))
return frame.Write(s.bw)
}