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.

101 lines
2.4 KiB

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