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.

287 lines
6.8 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
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
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. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net"
  8. "sync"
  9. "github.com/aceld/zinx/utils"
  10. "github.com/aceld/zinx/ziface"
  11. )
  12. //Connection 链接
  13. type Connection struct {
  14. //当前Conn属于哪个Server
  15. TCPServer ziface.IServer
  16. //当前连接的socket TCP套接字
  17. Conn *net.TCPConn
  18. //当前连接的ID 也可以称作为SessionID,ID全局唯一
  19. ConnID uint32
  20. //消息管理MsgID和对应处理方法的消息管理模块
  21. MsgHandler ziface.IMsgHandle
  22. //告知该链接已经退出/停止的channel
  23. ctx context.Context
  24. cancel context.CancelFunc
  25. //无缓冲管道,用于读、写两个goroutine之间的消息通信
  26. msgChan chan []byte
  27. //有缓冲管道,用于读、写两个goroutine之间的消息通信
  28. msgBuffChan chan []byte
  29. sync.RWMutex
  30. //链接属性
  31. property map[string]interface{}
  32. ////保护当前property的锁
  33. propertyLock sync.Mutex
  34. //当前连接的关闭状态
  35. isClosed bool
  36. }
  37. //NewConntion 创建连接的方法
  38. func NewConntion(server ziface.IServer, conn *net.TCPConn, connID uint32, msgHandler ziface.IMsgHandle) *Connection {
  39. //初始化Conn属性
  40. c := &Connection{
  41. TCPServer: server,
  42. Conn: conn,
  43. ConnID: connID,
  44. isClosed: false,
  45. MsgHandler: msgHandler,
  46. msgChan: make(chan []byte),
  47. msgBuffChan: make(chan []byte, utils.GlobalObject.MaxMsgChanLen),
  48. property: nil,
  49. }
  50. //将新创建的Conn添加到链接管理中
  51. c.TCPServer.GetConnMgr().Add(c)
  52. return c
  53. }
  54. //StartWriter 写消息Goroutine, 用户将数据发送给客户端
  55. func (c *Connection) StartWriter() {
  56. fmt.Println("[Writer Goroutine is running]")
  57. defer fmt.Println(c.RemoteAddr().String(), "[conn Writer exit!]")
  58. for {
  59. select {
  60. case data := <-c.msgChan:
  61. //有数据要写给客户端
  62. if _, err := c.Conn.Write(data); err != nil {
  63. fmt.Println("Send Data error:, ", err, " Conn Writer exit")
  64. return
  65. }
  66. //fmt.Printf("Send data succ! data = %+v\n", data)
  67. case data, ok := <-c.msgBuffChan:
  68. if ok {
  69. //有数据要写给客户端
  70. if _, err := c.Conn.Write(data); err != nil {
  71. fmt.Println("Send Buff Data error:, ", err, " Conn Writer exit")
  72. return
  73. }
  74. } else {
  75. fmt.Println("msgBuffChan is Closed")
  76. break
  77. }
  78. case <-c.ctx.Done():
  79. return
  80. }
  81. }
  82. }
  83. //StartReader 读消息Goroutine,用于从客户端中读取数据
  84. func (c *Connection) StartReader() {
  85. fmt.Println("[Reader Goroutine is running]")
  86. defer fmt.Println(c.RemoteAddr().String(), "[conn Reader exit!]")
  87. defer c.Stop()
  88. for {
  89. select {
  90. case <-c.ctx.Done():
  91. return
  92. default:
  93. // 创建拆包解包的对象
  94. dp := NewDataPack()
  95. //读取客户端的Msg head
  96. headData := make([]byte, dp.GetHeadLen())
  97. if _, err := io.ReadFull(c.Conn, headData); err != nil {
  98. fmt.Println("read msg head error ", err)
  99. return
  100. }
  101. //fmt.Printf("read headData %+v\n", headData)
  102. //拆包,得到msgID 和 datalen 放在msg中
  103. msg, err := dp.Unpack(headData)
  104. if err != nil {
  105. fmt.Println("unpack error ", err)
  106. return
  107. }
  108. //根据 dataLen 读取 data,放在msg.Data中
  109. var data []byte
  110. if msg.GetDataLen() > 0 {
  111. data = make([]byte, msg.GetDataLen())
  112. if _, err := io.ReadFull(c.Conn, data); err != nil {
  113. fmt.Println("read msg data error ", err)
  114. return
  115. }
  116. }
  117. msg.SetData(data)
  118. //得到当前客户端请求的Request数据
  119. req := Request{
  120. conn: c,
  121. msg: msg,
  122. }
  123. if utils.GlobalObject.WorkerPoolSize > 0 {
  124. //已经启动工作池机制,将消息交给Worker处理
  125. c.MsgHandler.SendMsgToTaskQueue(&req)
  126. } else {
  127. //从绑定好的消息和对应的处理方法中执行对应的Handle方法
  128. go c.MsgHandler.DoMsgHandler(&req)
  129. }
  130. }
  131. }
  132. }
  133. //Start 启动连接,让当前连接开始工作
  134. func (c *Connection) Start() {
  135. c.ctx, c.cancel = context.WithCancel(context.Background())
  136. //1 开启用户从客户端读取数据流程的Goroutine
  137. go c.StartReader()
  138. //2 开启用于写回客户端数据流程的Goroutine
  139. go c.StartWriter()
  140. //按照用户传递进来的创建连接时需要处理的业务,执行钩子方法
  141. c.TCPServer.CallOnConnStart(c)
  142. }
  143. //Stop 停止连接,结束当前连接状态M
  144. func (c *Connection) Stop() {
  145. c.Lock()
  146. defer c.Unlock()
  147. c.TCPServer.CallOnConnStop(c)
  148. //如果当前链接已经关闭
  149. if c.isClosed == true {
  150. return
  151. }
  152. fmt.Println("Conn Stop()...ConnID = ", c.ConnID)
  153. //如果用户注册了该链接的关闭回调业务,那么在此刻应该显示调用
  154. c.TcpServer.CallOnConnStop(c)
  155. // 关闭socket链接
  156. c.Conn.Close()
  157. //关闭Writer
  158. c.cancel()
  159. //将链接从连接管理器中删除
  160. c.TCPServer.GetConnMgr().Remove(c)
  161. //关闭该链接全部管道
  162. close(c.msgBuffChan)
  163. //设置标志位
  164. c.isClosed = true
  165. }
  166. //GetTCPConnection 从当前连接获取原始的socket TCPConn
  167. func (c *Connection) GetTCPConnection() *net.TCPConn {
  168. return c.Conn
  169. }
  170. //GetConnID 获取当前连接ID
  171. func (c *Connection) GetConnID() uint32 {
  172. return c.ConnID
  173. }
  174. //RemoteAddr 获取远程客户端地址信息
  175. func (c *Connection) RemoteAddr() net.Addr {
  176. return c.Conn.RemoteAddr()
  177. }
  178. //SendMsg 直接将Message数据发送数据给远程的TCP客户端
  179. func (c *Connection) SendMsg(msgID uint32, data []byte) error {
  180. c.RLock()
  181. defer c.RUnlock()
  182. if c.isClosed == true {
  183. return errors.New("connection closed when send msg")
  184. }
  185. //将data封包,并且发送
  186. dp := NewDataPack()
  187. msg, err := dp.Pack(NewMsgPackage(msgID, data))
  188. if err != nil {
  189. fmt.Println("Pack error msg ID = ", msgID)
  190. return errors.New("Pack error msg ")
  191. }
  192. //写回客户端
  193. c.msgChan <- msg
  194. return nil
  195. }
  196. //SendBuffMsg 发生BuffMsg
  197. func (c *Connection) SendBuffMsg(msgID uint32, data []byte) error {
  198. c.RLock()
  199. defer c.RUnlock()
  200. if c.isClosed == true {
  201. return errors.New("Connection closed when send buff msg")
  202. }
  203. //将data封包,并且发送
  204. dp := NewDataPack()
  205. msg, err := dp.Pack(NewMsgPackage(msgID, data))
  206. if err != nil {
  207. fmt.Println("Pack error msg ID = ", msgID)
  208. return errors.New("Pack error msg ")
  209. }
  210. //写回客户端
  211. c.msgBuffChan <- msg
  212. return nil
  213. }
  214. //SetProperty 设置链接属性
  215. func (c *Connection) SetProperty(key string, value interface{}) {
  216. c.propertyLock.Lock()
  217. defer c.propertyLock.Unlock()
  218. if c.property == nil {
  219. c.property = make(map[string]interface{})
  220. }
  221. c.property[key] = value
  222. }
  223. //GetProperty 获取链接属性
  224. func (c *Connection) GetProperty(key string) (interface{}, error) {
  225. c.propertyLock.Lock()
  226. defer c.propertyLock.Unlock()
  227. if value, ok := c.property[key]; ok {
  228. return value, nil
  229. }
  230. return nil, errors.New("no property found")
  231. }
  232. //RemoveProperty 移除链接属性
  233. func (c *Connection) RemoveProperty(key string) {
  234. c.propertyLock.Lock()
  235. defer c.propertyLock.Unlock()
  236. delete(c.property, key)
  237. }
  238. //返回ctx,用于用户自定义的go程获取连接退出状态
  239. func (c *Connection) Context() context.Context {
  240. return c.ctx
  241. }