You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.1 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package connection
import (
"net"
"sync"
"time"
"github.com/rs/xid"
)
// UnixConnection Unix Domain Socket连接包装器
type UnixConnection struct {
id string
conn net.Conn
mu sync.RWMutex
createdAt time.Time
lastActive time.Time
attributes map[string]interface{}
}
// NewUnixConnection 创建Unix连接
// 如果id为空将自动生成唯一的xid
func NewUnixConnection(id string, conn net.Conn) *UnixConnection {
if id == "" {
id = xid.New().String()
}
return &UnixConnection{
id: id,
conn: conn,
createdAt: time.Now(),
lastActive: time.Now(),
attributes: make(map[string]interface{}),
}
}
// ID 获取连接ID
func (c *UnixConnection) ID() string {
return c.id
}
// RemoteAddr 获取远程地址
func (c *UnixConnection) RemoteAddr() string {
if c.conn != nil {
return c.conn.RemoteAddr().String()
}
return ""
}
// LocalAddr 获取本地地址
func (c *UnixConnection) LocalAddr() string {
if c.conn != nil {
return c.conn.LocalAddr().String()
}
return ""
}
// Write 写入数据
func (c *UnixConnection) Write(data []byte) error {
c.mu.Lock()
c.lastActive = time.Now()
c.mu.Unlock()
if c.conn != nil {
_, err := c.conn.Write(data)
return err
}
return nil
}
// Close 关闭连接
func (c *UnixConnection) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
}
// SetAttribute 设置属性
func (c *UnixConnection) SetAttribute(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
if c.attributes == nil {
c.attributes = make(map[string]interface{})
}
c.attributes[key] = value
}
// GetAttribute 获取属性
func (c *UnixConnection) GetAttribute(key string) interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
if c.attributes == nil {
return nil
}
return c.attributes[key]
}
// LastActive 获取最后活动时间
func (c *UnixConnection) LastActive() time.Time {
c.mu.RLock()
defer c.mu.RUnlock()
return c.lastActive
}
// UpdateActive 更新活动时间
func (c *UnixConnection) UpdateActive() {
c.mu.Lock()
defer c.mu.Unlock()
c.lastActive = time.Now()
}