使用GoLang开发游戏服务器(九)

使用GoLang开发游戏服务器(九)

连接管理模块

服务器需要存储每个连接进入服务器的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中 新增
    在这里插入图片描述
    在这里插入图片描述
  • 实现接口
    在这里插入图片描述
  • 集成到框架中
    在这里插入图片描述
    在这里插入图片描述
  • 在外部使用
    在这里插入图片描述
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值