Ai
1 Star 6 Fork 4

夏季的风/TCP-UDP网络组件

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ConnManager.go 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
lingbinbin 提交于 2022-10-18 17:52 +08:00 . *修改UDP清理逻辑
package netService
import (
"gitee.com/ling-bin/network/netInterface"
"sync"
"sync/atomic"
)
//ConnManager 连接管理模块
type ConnManager struct {
connections sync.Map //连接记录
count int32 //连接数
}
//NewConnManager 实例化管理
func NewConnManager() netInterface.IConnManager {
return &ConnManager{}
}
//Add 添加链接[新连接处理]
func (c *ConnManager) Add(conn netInterface.IConnection) bool{
connId := conn.GetConnId()
_,ok := c.connections.LoadOrStore(connId, conn)
if !ok {
atomic.AddInt32(&c.count,1)
//fmt.Println("增加")
return true
}
return false
}
//Remove 删除连接
func (c *ConnManager) Remove(conn netInterface.IConnection) bool {
connId := conn.GetConnId()
return c.RemoveById(connId)
}
//RemoveById 删除连接
func (c *ConnManager) RemoveById(connId uint64) bool {
_,ok := c.connections.LoadAndDelete(connId)
//fmt.Println("----开始减少")
if ok {
atomic.AddInt32(&c.count,-1)
//fmt.Println("减少")
return true
}
return false
}
//Get 利用ConnID获取链接
func (c *ConnManager) Get(connId uint64) (netInterface.IConnection, bool) {
load, ok := c.connections.Load(connId)
if ok {
return load.(netInterface.IConnection), ok
}
return nil, false
}
//Range 遍历连接
func (c *ConnManager) Range(hFunc func(connId uint64, value netInterface.IConnection) bool) {
c.connections.Range(func(key, value interface{}) bool {
return hFunc(key.(uint64), value.(netInterface.IConnection))
})
}
//Count 获取个数
func (c *ConnManager) Count() int32 {
return c.count
}
//ClearConn 清除并停止所有连接
func (c *ConnManager) ClearConn() {
c.connections.Range(func(key, value interface{}) bool {
c.RemoveById(key.(uint64))
return true
})
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ling-bin/network.git
git@gitee.com:ling-bin/network.git
ling-bin
network
TCP-UDP网络组件
v1.8.30

搜索帮助