新增处理

This commit is contained in:
2024-12-24 14:07:17 +08:00
parent 6e4b37776b
commit 2a2e15c3d0
5 changed files with 36 additions and 121 deletions

View File

@@ -12,31 +12,30 @@ import (
"time"
)
// Server 定义 TCP 服务器结构
type Server struct {
Address string // 监听地址
Handler func(net.Conn) // 客户端连接处理函数
listener net.Listener // TCP 监听器
connections sync.Map // 活跃的客户端连接
wg sync.WaitGroup // 等待所有 Goroutine 完成
stopChan chan struct{} // 关闭信号
Address string
Handler func(net.Conn)
listener net.Listener
connections sync.Map
wg sync.WaitGroup
stopChan chan struct{}
clients map[string]*Client
clientsMux sync.RWMutex
stopOnce sync.Once // 添加 sync.Once 来确保 Stop 只被执行一次
stopOnce sync.Once
}
// Client 定义客户端结构
type Client struct {
ID string
Imei string // 添加 IMEI
Imei string
Conn net.Conn
ConnectedAt time.Time
LastPing time.Time
Done chan struct{}
IsAuth bool // 添加认证状态
authTimer *time.Timer // 添加登录超时定时器
IsAuth bool
authTimer *time.Timer
}
// NewServer 创建一个新的 TCP 服务器
@@ -49,7 +48,6 @@ func NewServer(address string, handler func(net.Conn)) *Server {
}
}
// Start 启动服务器
func (s *Server) Start() error {
var err error
s.listener, err = net.Listen("tcp", s.Address)
@@ -59,35 +57,31 @@ func (s *Server) Start() error {
fmt.Println("Listening and serving TCP on", s.Address)
// 捕获终止信号
go s.handleShutdown()
for {
// 非阻塞检查关闭信号
select {
case <-s.stopChan:
return nil
default:
}
// 接受新连接
conn, err := s.listener.Accept()
if err != nil {
select {
case <-s.stopChan:
return nil // 服务器已停止
return nil
default:
fmt.Println("Error accepting connection:", err)
continue
}
}
// 记录活跃连接并添加到 clients 映射
s.connections.Store(conn.RemoteAddr(), conn)
client := s.addClient(conn)
fmt.Printf("客户端已连接: %s\n", client.ID)
// 使用 Goroutine 处理客户端
s.wg.Add(1)
go func(c net.Conn, clientID string) {
defer s.wg.Done()
@@ -112,7 +106,6 @@ func (s *Server) handleShutdown() {
s.Stop()
}
// GetOnlineClients 获取所有在线客户端信息
func (s *Server) GetOnlineClients() []map[string]interface{} {
s.clientsMux.RLock()
defer s.clientsMux.RUnlock()
@@ -146,10 +139,8 @@ func (s *Server) addClient(conn net.Conn) *Client {
}
s.clients[client.ID] = client
// 启动心跳检测
go client.startHeartbeat(s)
// 添加登录超时检测
client.authTimer = time.AfterFunc(time.Minute, func() {
if !client.IsAuth {
fmt.Printf("Client %s authentication timeout\n", client.ID)
@@ -169,7 +160,7 @@ func (s *Server) removeClient(id string) {
client.authTimer.Stop()
client.authTimer = nil
}
close(client.Done) // 停止心跳检测
close(client.Done)
delete(s.clients, id)
}
}
@@ -179,13 +170,11 @@ func (s *Server) Stop() {
s.stopOnce.Do(func() {
fmt.Println("Stopping TCP server...")
// 关闭监听器
close(s.stopChan)
if s.listener != nil {
s.listener.Close()
}
// 关闭所有连接
s.clientsMux.Lock()
for id, client := range s.clients {
client.Conn.Close()
@@ -193,7 +182,6 @@ func (s *Server) Stop() {
}
s.clientsMux.Unlock()
// 等待所有 Goroutine 完成
s.wg.Wait()
fmt.Println("TCP server stopped.")
})
@@ -211,7 +199,7 @@ func (c *Client) startHeartbeat(s *Server) {
case <-ticker.C:
if time.Since(c.LastPing) > 120*time.Second {
fmt.Printf("客户端 %s 心跳超时 \n", c.ID)
c.Conn.Close() // 强制关闭连接
c.Conn.Close()
return
}
}