hpds_net_framework/tcpServer.go

60 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-08-03 16:55:40 +08:00
package hpds_net_framework
import (
"go.uber.org/zap"
"net"
"runtime/debug"
"sync"
"git.hpds.cc/Component/logging"
)
type tcpServer struct {
mu sync.Mutex
addr string
ln net.Listener
processor Processor
logger *logging.Logger
}
// NewTcpServer return new tcpServer
func NewTcpServer(addr string, processor Processor, logger *logging.Logger) (s *tcpServer, err error) {
ts := new(tcpServer)
ts.addr = addr
ts.ln, err = net.Listen("tcp", addr)
if processor == nil {
panic("processor must be set.")
}
ts.processor = processor
ts.logger = logger
if err != nil {
return nil, err
}
return ts, err
}
// Run the server
func (s *tcpServer) Run() error {
s.logger.Info("Starting tcp server", zap.String("address", s.addr))
for {
conn, err := s.ln.Accept()
if err != nil {
return err
}
go s.Handle(conn)
}
}
// Handle goroutine handle connection
func (s *tcpServer) Handle(conn net.Conn) {
defer func() {
if r := recover(); r != nil {
s.logger.Error("TCP handle panic", zap.Any("PANIC", r),
zap.ByteString("stack", debug.Stack()))
}
}()
var ic IConnection
ic = NewTcpConn(conn, s.processor, s.logger)
ic.ReadMsg()
}