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.

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