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.

131 lines
2.8 KiB

  1. package znet
  2. import (
  3. "fmt"
  4. "net"
  5. "zinx/ziface"
  6. )
  7. type Connection struct {
  8. //当前连接的socket TCP套接字
  9. Conn *net.TCPConn
  10. //当前连接的ID 也可以称作为SessionID,ID全局唯一
  11. ConnID uint32
  12. //当前连接的关闭状态
  13. isClosed bool
  14. //该连接的处理方法api
  15. handleAPI ziface.HandFunc
  16. //告知该链接已经退出/停止的channel
  17. ExitBuffChan chan bool
  18. //给缓冲队列发送数据的channel,
  19. // 如果向缓冲队列发送数据,那么把数据发送到这个channel下
  20. // SendBuffChan chan []byte
  21. }
  22. //创建连接的方法
  23. func NewConntion(conn *net.TCPConn, connID uint32, callback_api ziface.HandFunc) *Connection{
  24. c := &Connection{
  25. Conn: conn,
  26. ConnID: connID,
  27. isClosed: false,
  28. handleAPI: callback_api,
  29. ExitBuffChan: make(chan bool, 1),
  30. // SendBuffChan: make(chan []byte, 512),
  31. }
  32. return c
  33. }
  34. func (c *Connection) StartReader() {
  35. fmt.Println("Reader Goroutine is running")
  36. defer fmt.Println(c.RemoteAddr().String(), " conn reader exit!")
  37. defer c.Stop()
  38. for {
  39. //读取我们最大的数据到buf中
  40. buf := make([]byte, 512)
  41. cnt, err := c.Conn.Read(buf)
  42. if err != nil {
  43. fmt.Println("recv buf err ", err)
  44. c.ExitBuffChan <- true
  45. continue
  46. }
  47. //调用当前链接业务
  48. if err := c.handleAPI(c.Conn, buf, cnt); err !=nil {
  49. fmt.Println("connID ", c.ConnID, " handle is error")
  50. c.ExitBuffChan <- true
  51. return
  52. }
  53. }
  54. }
  55. //启动连接,让当前连接开始工作
  56. func (c *Connection) Start() {
  57. //开启处理该链接读取到客户端数据之后的请求业务
  58. go c.StartReader()
  59. for {
  60. select {
  61. case <- c.ExitBuffChan:
  62. //得到退出消息,不再阻塞
  63. return
  64. }
  65. }
  66. //1 开启用于写回客户端数据流程的Goroutine
  67. //2 开启用户从客户端读取数据流程的Goroutine
  68. }
  69. //停止连接,结束当前连接状态M
  70. func (c *Connection) Stop() {
  71. //1. 如果当前链接已经关闭
  72. if c.isClosed == true {
  73. return
  74. }
  75. c.isClosed = true
  76. //TODO Connection Stop() 如果用户注册了该链接的关闭回调业务,那么在此刻应该显示调用
  77. // 关闭socket链接
  78. c.Conn.Close()
  79. //通知从缓冲队列读数据的业务,该链接已经关闭
  80. c.ExitBuffChan <- true
  81. //关闭该链接全部管道
  82. //close(c.ExitBuffChan)
  83. //close(c.SendBuffChan)
  84. }
  85. //从当前连接获取原始的socket TCPConn
  86. func (c *Connection) GetTCPConnection() *net.TCPConn {
  87. return c.Conn
  88. }
  89. //获取当前连接ID
  90. func (c *Connection) GetConnID() uint32{
  91. return c.ConnID
  92. }
  93. //获取远程客户端地址信息
  94. func (c *Connection) RemoteAddr() net.Addr {
  95. return c.Conn.RemoteAddr()
  96. }
  97. //直接将数据发送数据给远程的TCP客户端
  98. func (c *Connection) Send(data []byte) error {
  99. return nil
  100. }
  101. //将数据发送给缓冲队列,通过专门从缓冲队列读数据的go写给客户端
  102. func (c *Connection) SendBuff(data []byte) error {
  103. return nil
  104. }