You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.9 KiB

  1. package znet
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/aceld/zinx/ziface"
  6. "sync"
  7. )
  8. /*
  9. 连接管理模块
  10. */
  11. type ConnManager struct {
  12. connections map[uint32]ziface.IConnection //管理的连接信息
  13. connLock sync.RWMutex //读写连接的读写锁
  14. }
  15. /*
  16. 创建一个链接管理
  17. */
  18. func NewConnManager() *ConnManager {
  19. return &ConnManager{
  20. connections: make(map[uint32]ziface.IConnection),
  21. }
  22. }
  23. //添加链接
  24. func (connMgr *ConnManager) Add(conn ziface.IConnection) {
  25. //保护共享资源Map 加写锁
  26. connMgr.connLock.Lock()
  27. defer connMgr.connLock.Unlock()
  28. //将conn连接添加到ConnMananger中
  29. connMgr.connections[conn.GetConnID()] = conn
  30. fmt.Println("connection add to ConnManager successfully: conn num = ", connMgr.Len())
  31. }
  32. //删除连接
  33. func (connMgr *ConnManager) Remove(conn ziface.IConnection) {
  34. //保护共享资源Map 加写锁
  35. connMgr.connLock.Lock()
  36. defer connMgr.connLock.Unlock()
  37. //删除连接信息
  38. delete(connMgr.connections, conn.GetConnID())
  39. fmt.Println("connection Remove ConnID=", conn.GetConnID(), " successfully: conn num = ", connMgr.Len())
  40. }
  41. //利用ConnID获取链接
  42. func (connMgr *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
  43. //保护共享资源Map 加读锁
  44. connMgr.connLock.RLock()
  45. defer connMgr.connLock.RUnlock()
  46. if conn, ok := connMgr.connections[connID]; ok {
  47. return conn, nil
  48. } else {
  49. return nil, errors.New("connection not found")
  50. }
  51. }
  52. //获取当前连接
  53. func (connMgr *ConnManager) Len() int {
  54. return len(connMgr.connections)
  55. }
  56. //清除并停止所有连接
  57. func (connMgr *ConnManager) ClearConn() {
  58. //保护共享资源Map 加写锁
  59. connMgr.connLock.Lock()
  60. defer connMgr.connLock.Unlock()
  61. //停止并删除全部的连接信息
  62. for connID, conn := range connMgr.connections {
  63. //停止
  64. conn.Stop()
  65. //删除
  66. delete(connMgr.connections, connID)
  67. }
  68. fmt.Println("Clear All Connections successfully: conn num = ", connMgr.Len())
  69. }