修改代码
This commit is contained in:
@@ -60,7 +60,6 @@ func (s *Server) Start() error {
|
||||
go s.handleShutdown()
|
||||
|
||||
for {
|
||||
|
||||
select {
|
||||
case <-s.stopChan:
|
||||
return nil
|
||||
@@ -78,21 +77,36 @@ func (s *Server) Start() error {
|
||||
}
|
||||
}
|
||||
|
||||
s.connections.Store(conn.RemoteAddr(), conn)
|
||||
client := s.addClient(conn)
|
||||
fmt.Printf("客户端已连接: %s\n", client.ID)
|
||||
// 创建临时客户端,不加入 clients map
|
||||
tempClient := &Client{
|
||||
ID: conn.RemoteAddr().String(),
|
||||
Conn: conn,
|
||||
ConnectedAt: time.Now(),
|
||||
LastPing: time.Now(),
|
||||
Done: make(chan struct{}),
|
||||
}
|
||||
|
||||
// 设置认证超时
|
||||
time.AfterFunc(time.Minute, func() {
|
||||
if !tempClient.IsAuth {
|
||||
fmt.Printf("Client %s authentication timeout\n", tempClient.ID)
|
||||
conn.Close()
|
||||
}
|
||||
})
|
||||
|
||||
s.wg.Add(1)
|
||||
go func(c net.Conn, clientID string) {
|
||||
go func(c net.Conn, client *Client) {
|
||||
defer s.wg.Done()
|
||||
defer func() {
|
||||
s.connections.Delete(c.RemoteAddr())
|
||||
s.removeClient(clientID)
|
||||
if client.IsAuth {
|
||||
s.removeClient(client.ID)
|
||||
}
|
||||
c.Close()
|
||||
fmt.Printf("客户端已断开连接: %s\n", clientID)
|
||||
fmt.Printf("客户端已断开连接: %s\n", client.ID)
|
||||
}()
|
||||
s.Handler(c)
|
||||
}(conn, client.ID)
|
||||
}(conn, tempClient)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,29 +140,13 @@ func (s *Server) GetOnlineClients() []map[string]interface{} {
|
||||
}
|
||||
|
||||
// addClient 添加新客户端
|
||||
func (s *Server) addClient(conn net.Conn) *Client {
|
||||
func (s *Server) addClient(client *Client) {
|
||||
s.clientsMux.Lock()
|
||||
defer s.clientsMux.Unlock()
|
||||
|
||||
client := &Client{
|
||||
ID: conn.RemoteAddr().String(),
|
||||
Conn: conn,
|
||||
ConnectedAt: time.Now(),
|
||||
LastPing: time.Now(),
|
||||
Done: make(chan struct{}),
|
||||
}
|
||||
s.clients[client.ID] = client
|
||||
|
||||
// 使用 IMEI 作为 key
|
||||
s.clients[client.Imei] = client
|
||||
go client.startHeartbeat(s)
|
||||
|
||||
client.authTimer = time.AfterFunc(time.Minute, func() {
|
||||
if !client.IsAuth {
|
||||
fmt.Printf("Client %s authentication timeout\n", client.ID)
|
||||
client.Conn.Close() // 强制关闭连接
|
||||
}
|
||||
})
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
// removeClient 移除客户端
|
||||
|
||||
Reference in New Issue
Block a user