10.2 链接属性方法实现

zinx/znet/connction.go

  1. type Connection struct {
  2. //当前Conn属于哪个Server
  3. TcpServer ziface.IServer
  4. //当前连接的socket TCP套接字
  5. Conn *net.TCPConn
  6. //当前连接的ID 也可以称作为SessionID,ID全局唯一
  7. ConnID uint32
  8. //当前连接的关闭状态
  9. isClosed bool
  10. //消息管理MsgId和对应处理方法的消息管理模块
  11. MsgHandler ziface.IMsgHandle
  12. //告知该链接已经退出/停止的channel
  13. ExitBuffChan chan bool
  14. //无缓冲管道,用于读、写两个goroutine之间的消息通信
  15. msgChan chan []byte
  16. //有关冲管道,用于读、写两个goroutine之间的消息通信
  17. msgBuffChan chan []byte
  18. // ================================
  19. //链接属性
  20. property map[string]interface{}
  21. //保护链接属性修改的锁
  22. propertyLock sync.RWMutex
  23. // ================================
  24. }
  25. //创建连接的方法
  26. func NewConntion(server ziface.IServer, conn *net.TCPConn, connID uint32, msgHandler ziface.IMsgHandle) *Connection {
  27. //初始化Conn属性
  28. c := &Connection{
  29. TcpServer: server,
  30. Conn: conn,
  31. ConnID: connID,
  32. isClosed: false,
  33. MsgHandler: msgHandler,
  34. ExitBuffChan: make(chan bool, 1),
  35. msgChan: make(chan []byte),
  36. msgBuffChan: make(chan []byte, utils.GlobalObject.MaxMsgChanLen),
  37. property: make(map[string]interface{}), //对链接属性map初始化
  38. }
  39. //将新创建的Conn添加到链接管理中
  40. c.TcpServer.GetConnMgr().Add(c)
  41. return c
  42. }
  43. // ...
  44. //设置链接属性
  45. func (c *Connection) SetProperty(key string, value interface{}) {
  46. c.propertyLock.Lock()
  47. defer c.propertyLock.Unlock()
  48. c.property[key] = value
  49. }
  50. //获取链接属性
  51. func (c *Connection) GetProperty(key string) (interface{}, error) {
  52. c.propertyLock.RLock()
  53. defer c.propertyLock.RUnlock()
  54. if value, ok := c.property[key]; ok {
  55. return value, nil
  56. } else {
  57. return nil, errors.New("no property found")
  58. }
  59. }
  60. //移除链接属性
  61. func (c *Connection) RemoveProperty(key string) {
  62. c.propertyLock.Lock()
  63. defer c.propertyLock.Unlock()
  64. delete(c.property, key)
  65. }