package network import ( "git.hpds.cc/Component/network/log" "sync" ) var _ Connector = &connector{} // Connector is an interface to manage the connections and applications. type Connector interface { // Add a connection. Add(connId string, conn Connection) // Remove a connection. Remove(connId string) // Get a connection by connection id. Get(connId string) Connection // GetSnapshot gets the snapshot of all connections. GetSnapshot() map[string]string // GetProtocolGatewayConnections gets the connections by Protocol Gateway observe tags. GetProtocolGatewayConnections(sourceId string, tags byte) []Connection // Clean the connector. Clean() } type connector struct { conns sync.Map } func newConnector() Connector { return &connector{conns: sync.Map{}} } // Add a connection. func (c *connector) Add(connID string, conn Connection) { log.Debugf("%sconnector add: connId=%s", ServerLogPrefix, connID) c.conns.Store(connID, conn) } // Remove a connection. func (c *connector) Remove(connID string) { log.Debugf("%sconnector remove: connId=%s", ServerLogPrefix, connID) c.conns.Delete(connID) } // Get a connection by connection id. func (c *connector) Get(connID string) Connection { log.Debugf("%sconnector get connection: connId=%s", ServerLogPrefix, connID) if conn, ok := c.conns.Load(connID); ok { return conn.(Connection) } return nil } // GetProtocolGatewayConnections gets the Protocol Gateway connection by tag. func (c *connector) GetProtocolGatewayConnections(sourceId string, tag byte) []Connection { conns := make([]Connection, 0) c.conns.Range(func(key interface{}, val interface{}) bool { conn := val.(Connection) for _, v := range conn.ObserveDataTags() { if v == tag && conn.ClientType() == ClientTypeProtocolGateway && conn.ClientId() == sourceId { conns = append(conns, conn) } } return true }) return conns } // GetSnapshot gets the snapshot of all connections. func (c *connector) GetSnapshot() map[string]string { result := make(map[string]string) c.conns.Range(func(key interface{}, val interface{}) bool { connID := key.(string) conn := val.(Connection) result[connID] = conn.Name() return true }) return result } // Clean the connector. func (c *connector) Clean() { c.conns = sync.Map{} }