GAAS GFrame项目web后台
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.

67 lines
1.6 KiB

package messaging
import (
"github.com/kataras/neffos"
"sync"
)
type Contexts struct {
locker sync.RWMutex
connections map[string]*neffos.NSConn
callbacksOfAdd []func(string, *neffos.NSConn)
callbacksOfRemove []func(string)
authenticator func(map[string]string) (string, error)
}
func newContexts() *Contexts {
return &Contexts{
connections: make(map[string]*neffos.NSConn, 10),
callbacksOfAdd: make([]func(string, *neffos.NSConn), 0, 10),
callbacksOfRemove: make([]func(string), 0, 10),
}
}
func (contexts *Contexts) add(id string, connection *neffos.NSConn) {
locker.Lock()
defer locker.Unlock()
contexts.connections[id] = connection
for _, callback := range contexts.callbacksOfAdd {
callback(id, connection)
}
}
func (contexts *Contexts) remove(id string) {
locker.Lock()
defer locker.Unlock()
delete(contexts.connections, id)
for _, callback := range contexts.callbacksOfRemove {
callback(id)
}
}
func (contexts *Contexts) Get(id string) *neffos.NSConn {
locker.RLock()
defer locker.RUnlock()
connection, ok := contexts.connections[id]
if ok {
return connection
} else {
return nil
}
}
func (contexts *Contexts) OnAdd(callback func(string, *neffos.NSConn)) {
locker.Lock()
defer locker.Unlock()
contexts.callbacksOfAdd = append(contexts.callbacksOfAdd, callback)
}
func (contexts *Contexts) OnRemove(callback func(string)) {
locker.Lock()
defer locker.Unlock()
contexts.callbacksOfRemove = append(contexts.callbacksOfRemove, callback)
}
func (contexts *Contexts) SetAuthenticator(authenticator func(map[string]string) (string, error)) {
contexts.authenticator = authenticator
}