Files
proxy/server/fwd/fwd.go

83 lines
1.3 KiB
Go
Raw Normal View History

package fwd
import (
"context"
"log/slog"
"proxy-server/pkg/utils"
"proxy-server/server/core"
2025-02-27 23:11:36 +08:00
"sync"
)
type Service struct {
ctx context.Context
cancel context.CancelFunc
userConnMap core.SyncMap[string, *core.Conn]
2025-02-27 23:11:36 +08:00
fwdLesWg utils.CountWaitGroup
ctrlConnWg utils.CountWaitGroup
dataConnWg utils.CountWaitGroup
userConnWg utils.CountWaitGroup
}
func New() *Service {
2025-02-27 23:11:36 +08:00
ctx, cancel := context.WithCancel(context.Background())
return &Service{
ctx: ctx,
cancel: cancel,
}
}
2025-05-14 15:13:44 +08:00
func (s *Service) Run() error {
slog.Debug("启动转发服务")
2025-03-06 14:35:21 +08:00
errQuit := make(chan struct{}, 2)
2025-02-27 23:11:36 +08:00
defer close(errQuit)
2025-02-27 23:11:36 +08:00
wg := sync.WaitGroup{}
// 控制通道
2025-02-27 23:11:36 +08:00
wg.Add(1)
go func() {
defer wg.Done()
err := s.listenCtrl()
if err != nil {
slog.Error("fwd 控制通道监听发生错误", "err", err)
2025-02-27 23:11:36 +08:00
errQuit <- struct{}{}
return
}
}()
// 数据通道
2025-02-27 23:11:36 +08:00
wg.Add(1)
go func() {
defer wg.Done()
err := s.listenData()
2025-02-27 23:11:36 +08:00
if err != nil {
slog.Error("fwd 数据通道监听发生错误", "err", err)
2025-02-27 23:11:36 +08:00
errQuit <- struct{}{}
return
}
2025-02-27 23:11:36 +08:00
}()
// 等待退出
2025-02-27 23:11:36 +08:00
select {
case <-s.ctx.Done():
case <-errQuit:
slog.Warn("fwd 服务异常退出")
2025-05-14 15:13:44 +08:00
s.Stop()
}
wg.Wait()
s.fwdLesWg.Wait()
s.ctrlConnWg.Wait()
s.userConnWg.Wait()
s.dataConnWg.Wait()
2025-05-14 15:13:44 +08:00
return nil
}
func (s *Service) Stop() {
s.cancel()
2025-02-27 18:07:00 +08:00
}