| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- // Author: simon (ynwdlxm@163.com)
- // Date: 2025/9/12 11:02
- // Desc: 对每个连接进行封装(第个客服连接的描述)
- package connection
- import (
- "net"
- "sync"
- "time"
- "github.com/runningwater/go-redis/lib/logger"
- "github.com/runningwater/go-redis/lib/sync/wait"
- )
- type Connection struct {
- conn net.Conn
- waiting wait.Wait
- mu sync.Mutex
- selectedDB int
- }
- func NewConnection(conn net.Conn) *Connection {
- return &Connection{
- conn: conn,
- }
- }
- func (c *Connection) RemoteAddr() net.Addr {
- return c.conn.RemoteAddr()
- }
- func (c *Connection) Close() error {
- timeout := c.waiting.WaitWithTimeout(10 * time.Second)
- if timeout {
- logger.Info("timeout to close connection")
- } else {
- logger.Info("connection closed")
- }
- err := c.conn.Close()
- return err
- }
- func (c *Connection) Write(bytes []byte) error {
- if len(bytes) == 0 {
- return nil
- }
- logger.InfoC("write to client: ", string(bytes))
- c.mu.Lock()
- c.waiting.Add(1)
- defer func() {
- c.waiting.Done()
- c.mu.Unlock()
- }()
- _, err := c.conn.Write(bytes)
- return err
- }
- func (c *Connection) GetDBIndex() int {
- return c.selectedDB
- }
- func (c *Connection) SelectDB(dbNum int) {
- c.selectedDB = dbNum
- }
|