连接管理模块
服务器需要存储每个连接进入服务器的connection对象,以便于进行管理
- 新增接口IConnectionManager
type IConnectionManager interface {
AddConnection(conn IConnection)
RemoveConnection(conn IConnection)
GetConnection(connID uint32) (IConnection, error)
GetConnectionsLength() int
ClearConnection()
}
- 新增结构体ConnectionManager
使用map管理每一个连接进来的客户端
使用读写锁,因为map中的对象要在不同的Goroutine中进行增删改
type ConnectionManager struct {
connections map[uint32]ziface.IConnection
connectionLock sync.RWMutex
}
func (c *ConnectionManager) AddConnection(conn ziface.IConnection) {
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
c.connections[conn.GetConnectionID()] = conn
fmt.Println("Add Connection To ConnectionManager!!! ConnectionID:", conn.GetConnectionID(), " RemoteAddr:", conn.RemoteAddr().String())
}
func (c *ConnectionManager) RemoveConnection(conn ziface.IConnection) {
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
delete(c.connections, conn.GetConnectionID())
fmt.Println("Remove Connection To ConnectionManager!!! ConnectionID:", conn.GetConnectionID(), " RemoteAddr:", conn.RemoteAddr().String())
}
func (c *ConnectionManager) GetConnection(connID uint32) (ziface.IConnection, error) {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if conn, ok := c.connections[connID]; ok {
return conn, nil
} else {
return nil, errors.New("Not Have ConnID:" + string(connID))
}
}
func (c *ConnectionManager) GetConnectionsLength() int {
return len(c.connections)
}
func (c *ConnectionManager) ClearConnection() {
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
for key, val := range c.connections {
val.Stop()
delete(c.connections, key)
}
fmt.Println("Clear All Connections To ConnectionManager!!!")
}
func NewConnectionManager() *ConnectionManager {
return &ConnectionManager{
connections: make(map[uint32]ziface.IConnection),
}
}
- 在Server结构体中新增属性
- 需要建立Conn对于Server的关系,某个Conn属于哪个Server中,所以Conn需要新增Server属性记录隶属于的Server
- 在创建Connection中就往ConnectionManager中添加Connection
- 在关闭Connection的时候就从ConnectionManager中移除Connection
- 在Server中若关闭了服务器,那么需要在Stop中将ConnectionManager中的Connection清除
- 为了限制服务器的最大承载的客户端数量,在Server的Start中
对外提供客户端接入和客户端断开的回调函数
- 在Server中 新增
- 实现接口
- 集成到框架中
- 在外部使用