mediamtx/internal/serverrtmp/server.go

93 lines
1.5 KiB
Go
Raw Normal View History

2021-01-31 15:58:57 +00:00
package serverrtmp
import (
"net"
"strconv"
"sync/atomic"
2021-01-31 15:58:57 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
)
// Parent is implemented by program.
type Parent interface {
Log(logger.Level, string, ...interface{})
}
// Server is a RTMP listener.
type Server struct {
parent Parent
l net.Listener
closed uint32
// out
accept chan net.Conn
done chan struct{}
2021-01-31 15:58:57 +00:00
}
// New allocates a Server.
func New(
listenIP string,
port int,
parent Parent) (*Server, error) {
address := listenIP + ":" + strconv.FormatInt(int64(port), 10)
l, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
s := &Server{
parent: parent,
l: l,
accept: make(chan net.Conn),
done: make(chan struct{}),
2021-01-31 15:58:57 +00:00
}
s.log(logger.Info, "opened on %s", address)
2021-01-31 15:58:57 +00:00
go s.run()
return s, nil
}
func (s *Server) log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[RTMP listener] "+format, append([]interface{}{}, args...)...)
}
2021-01-31 15:58:57 +00:00
// Close closes a Server.
func (s *Server) Close() {
go func() {
for co := range s.accept {
co.Close()
}
}()
atomic.StoreUint32(&s.closed, 1)
2021-01-31 15:58:57 +00:00
s.l.Close()
<-s.done
2021-01-31 15:58:57 +00:00
}
func (s *Server) run() {
defer close(s.done)
2021-01-31 15:58:57 +00:00
for {
nconn, err := s.l.Accept()
if err != nil {
if atomic.LoadUint32(&s.closed) == 1 {
break
}
s.log(logger.Warn, "ERR: %s", err)
continue
2021-01-31 15:58:57 +00:00
}
s.accept <- nconn
2021-01-31 15:58:57 +00:00
}
close(s.accept)
}
2021-01-31 15:58:57 +00:00
// Accept returns a channel to accept incoming connections.
func (s *Server) Accept() chan net.Conn {
return s.accept
2021-01-31 15:58:57 +00:00
}