conn.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Author: simon (ynwdlxm@163.com)
  2. // Date: 2025/9/12 11:02
  3. // Desc: 对每个连接进行封装(第个客服连接的描述)
  4. package connection
  5. import (
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/runningwater/go-redis/lib/logger"
  10. "github.com/runningwater/go-redis/lib/sync/wait"
  11. )
  12. type Connection struct {
  13. conn net.Conn
  14. waiting wait.Wait
  15. mu sync.Mutex
  16. selectedDB int
  17. }
  18. func NewConnection(conn net.Conn) *Connection {
  19. return &Connection{
  20. conn: conn,
  21. }
  22. }
  23. func (c *Connection) RemoteAddr() net.Addr {
  24. return c.conn.RemoteAddr()
  25. }
  26. func (c *Connection) Close() error {
  27. timeout := c.waiting.WaitWithTimeout(10 * time.Second)
  28. if timeout {
  29. logger.Info("timeout to close connection")
  30. } else {
  31. logger.Info("connection closed")
  32. }
  33. err := c.conn.Close()
  34. return err
  35. }
  36. func (c *Connection) Write(bytes []byte) error {
  37. if len(bytes) == 0 {
  38. return nil
  39. }
  40. logger.InfoC("write to client: ", string(bytes))
  41. c.mu.Lock()
  42. c.waiting.Add(1)
  43. defer func() {
  44. c.waiting.Done()
  45. c.mu.Unlock()
  46. }()
  47. _, err := c.conn.Write(bytes)
  48. return err
  49. }
  50. func (c *Connection) GetDBIndex() int {
  51. return c.selectedDB
  52. }
  53. func (c *Connection) SelectDB(dbNum int) {
  54. c.selectedDB = dbNum
  55. }