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.

170 lines
4.0 KiB

  1. package znet
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net"
  7. "zinx/ziface"
  8. )
  9. type Connection struct {
  10. //当前连接的socket TCP套接字
  11. Conn *net.TCPConn
  12. //当前连接的ID 也可以称作为SessionID,ID全局唯一
  13. ConnID uint32
  14. //当前连接的关闭状态
  15. isClosed bool
  16. //消息管理MsgId和对应处理方法的消息管理模块
  17. MsgHandler ziface.IMsgHandle
  18. //告知该链接已经退出/停止的channel
  19. ExitBuffChan chan bool
  20. //给缓冲队列发送数据的channel,
  21. // 如果向缓冲队列发送数据,那么把数据发送到这个channel下
  22. // SendBuffChan chan []byte
  23. }
  24. //创建连接的方法
  25. func NewConntion(conn *net.TCPConn, connID uint32, msgHandler ziface.IMsgHandle) *Connection{
  26. c := &Connection{
  27. Conn: conn,
  28. ConnID: connID,
  29. isClosed: false,
  30. MsgHandler: msgHandler,
  31. ExitBuffChan: make(chan bool, 1),
  32. // SendBuffChan: make(chan []byte, 512),
  33. }
  34. return c
  35. }
  36. func (c *Connection) StartReader() {
  37. fmt.Println("Reader Goroutine is running")
  38. defer fmt.Println(c.RemoteAddr().String(), " conn reader exit!")
  39. defer c.Stop()
  40. for {
  41. // 创建拆包解包的对象
  42. dp := NewDataPack()
  43. //读取客户端的Msg head
  44. headData := make([]byte, dp.GetHeadLen())
  45. if _, err := io.ReadFull(c.GetTCPConnection(), headData); err != nil {
  46. fmt.Println("read msg head error ", err)
  47. c.ExitBuffChan <- true
  48. continue
  49. }
  50. //拆包,得到msgid 和 datalen 放在msg中
  51. msg , err := dp.Unpack(headData)
  52. if err != nil {
  53. fmt.Println("unpack error ", err)
  54. c.ExitBuffChan <- true
  55. continue
  56. }
  57. //根据 dataLen 读取 data,放在msg.Data中
  58. var data []byte
  59. if msg.GetDataLen() > 0 {
  60. data = make([]byte, msg.GetDataLen())
  61. if _, err := io.ReadFull(c.GetTCPConnection(), data); err != nil {
  62. fmt.Println("read msg data error ", err)
  63. c.ExitBuffChan <- true
  64. continue
  65. }
  66. }
  67. msg.SetData(data)
  68. //得到当前客户端请求的Request数据
  69. req := Request{
  70. conn:c,
  71. msg:msg,
  72. }
  73. //从绑定好的消息和对应的处理方法中执行对应的Handle方法
  74. go c.MsgHandler.DoMsgHandler(&req)
  75. }
  76. }
  77. //启动连接,让当前连接开始工作
  78. func (c *Connection) Start() {
  79. //开启处理该链接读取到客户端数据之后的请求业务
  80. go c.StartReader()
  81. for {
  82. select {
  83. case <- c.ExitBuffChan:
  84. //得到退出消息,不再阻塞
  85. return
  86. }
  87. }
  88. //1 开启用于写回客户端数据流程的Goroutine
  89. //2 开启用户从客户端读取数据流程的Goroutine
  90. }
  91. //停止连接,结束当前连接状态M
  92. func (c *Connection) Stop() {
  93. //1. 如果当前链接已经关闭
  94. if c.isClosed == true {
  95. return
  96. }
  97. c.isClosed = true
  98. //TODO Connection Stop() 如果用户注册了该链接的关闭回调业务,那么在此刻应该显示调用
  99. // 关闭socket链接
  100. c.Conn.Close()
  101. //通知从缓冲队列读数据的业务,该链接已经关闭
  102. c.ExitBuffChan <- true
  103. //关闭该链接全部管道
  104. close(c.ExitBuffChan)
  105. //close(c.SendBuffChan)
  106. }
  107. //从当前连接获取原始的socket TCPConn
  108. func (c *Connection) GetTCPConnection() *net.TCPConn {
  109. return c.Conn
  110. }
  111. //获取当前连接ID
  112. func (c *Connection) GetConnID() uint32{
  113. return c.ConnID
  114. }
  115. //获取远程客户端地址信息
  116. func (c *Connection) RemoteAddr() net.Addr {
  117. return c.Conn.RemoteAddr()
  118. }
  119. //直接将Message数据发送数据给远程的TCP客户端
  120. func (c *Connection) SendMsg(msgId uint32, data []byte) error {
  121. if c.isClosed == true {
  122. return errors.New("Connection closed when send msg")
  123. }
  124. //将data封包,并且发送
  125. dp := NewDataPack()
  126. msg, err := dp.Pack(NewMsgPackage(msgId, data))
  127. if err != nil {
  128. fmt.Println("Pack error msg id = ", msgId)
  129. return errors.New("Pack error msg ")
  130. }
  131. //写回客户端
  132. if _, err := c.Conn.Write(msg); err != nil {
  133. fmt.Println("Write msg id ", msgId, " error ")
  134. c.ExitBuffChan <- true
  135. return errors.New("conn Write error")
  136. }
  137. return nil
  138. }
  139. //将数据发送给缓冲队列,通过专门从缓冲队列读数据的go写给客户端
  140. //func (c *Connection) SendBuff(data []byte) error {
  141. // return nil
  142. //}