You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package conn
import (
"git.noahlan.cn/noahlan/nnet/entity"
"sync"
)
var ConnManager * Manager
type Manager struct {
sync . RWMutex
// 分组
groups map [ string ] * Group
// 所有 Connection
conns map [ int64 ] entity . NetworkEntity
}
func init ( ) {
ConnManager = & Manager {
RWMutex : sync . RWMutex { } ,
groups : make ( map [ string ] * Group ) ,
conns : make ( map [ int64 ] entity . NetworkEntity ) ,
}
}
// Store 保存连接,同时加入到指定分组,若给定分组名为空,则不进行分组操作
func ( m * Manager ) Store ( groupName string , s entity . NetworkEntity ) {
m . Lock ( )
m . conns [ s . Session ( ) . ID ( ) ] = s
m . Unlock ( )
group , ok := m . FindGroup ( groupName )
if ! ok {
group = m . NewGroup ( groupName )
}
_ = group . Add ( s )
}
// NewGroup 新增分组,若分组已存在,则返回现有分组
func ( m * Manager ) NewGroup ( name string ) * Group {
m . Lock ( )
defer m . Unlock ( )
group , ok := m . groups [ name ]
if ok {
return group
}
group = NewGroup ( name )
m . groups [ name ] = group
return group
}
// FindGroup 查找分组
func ( m * Manager ) FindGroup ( name string ) ( * Group , bool ) {
m . RLock ( )
defer m . RUnlock ( )
g , ok := m . groups [ name ]
return g , ok
}
// FindConn 根据连接ID找到连接
func ( m * Manager ) FindConn ( id int64 ) ( entity . NetworkEntity , bool ) {
m . RLock ( )
defer m . RUnlock ( )
e , ok := m . conns [ id ]
return e , ok
}
// FindConnByUID 根据连接绑定的UID找到连接
func ( m * Manager ) FindConnByUID ( uid string ) ( entity . NetworkEntity , bool ) {
m . RLock ( )
defer m . RUnlock ( )
for _ , e := range m . conns {
if e . Session ( ) . UID ( ) == uid {
return e , true
}
}
return nil , false
}
// PeekConn 循环所有连接
// fn 返回true跳过循环, 反之一直循环
func ( m * Manager ) PeekConn ( fn func ( id int64 , e entity . NetworkEntity ) bool ) {
m . RLock ( )
defer m . RUnlock ( )
for id , e := range m . conns {
if fn ( id , e ) {
break
}
}
}