2017-09-05 16:48:19 +09:00

112 lines
2.1 KiB
Go

package server
import (
uch "git.loafle.net/commons_go/util/channel"
ogw "git.loafle.net/overflow/overflow_gateway_websocket"
)
type socketsChannelAction struct {
uch.Action
uid string
soc ogw.Socket
}
type SocketManager interface {
AddSocket(uid string, soc ogw.Socket)
RemoveSocket(soc ogw.Socket)
GetSocket(uid string) ogw.Socket
GetUID(soc ogw.Socket) string
}
type socketManager struct {
sockets map[string]ogw.Socket
socketsR map[ogw.Socket]string
socketsCh chan socketsChannelAction
}
var _m SocketManager
func init() {
_m = New()
}
func New() SocketManager {
m := &socketManager{
sockets: make(map[string]ogw.Socket),
socketsR: make(map[ogw.Socket]string),
socketsCh: make(chan socketsChannelAction),
}
go m.listenChannel()
return m
}
func AddSocket(uid string, soc ogw.Socket) { _m.AddSocket(uid, soc) }
func (m *socketManager) AddSocket(uid string, soc ogw.Socket) {
ca := socketsChannelAction{
uid: uid,
soc: soc,
}
ca.Type = uch.ActionTypeCreate
m.socketsCh <- ca
}
func RemoveSocket(soc ogw.Socket) { _m.RemoveSocket(soc) }
func (m *socketManager) RemoveSocket(soc ogw.Socket) {
ca := socketsChannelAction{
soc: soc,
}
ca.Type = uch.ActionTypeDelete
m.socketsCh <- ca
}
func GetSocket(uid string) ogw.Socket { return _m.GetSocket(uid) }
func (m *socketManager) GetSocket(uid string) ogw.Socket {
var ok bool
var soc ogw.Socket
if soc, ok = m.sockets[uid]; !ok {
return nil
}
return soc
}
func GetUID(soc ogw.Socket) string { return _m.GetUID(soc) }
func (m *socketManager) GetUID(soc ogw.Socket) string {
var ok bool
var uid string
if uid, ok = m.socketsR[soc]; !ok {
return ""
}
return uid
}
func (m *socketManager) _removeSocket(ca *socketsChannelAction) {
var uid string
var ok bool
soc := ca.soc
if uid, ok = m.socketsR[soc]; !ok {
return
}
delete(m.sockets, uid)
delete(m.socketsR, soc)
}
func (m *socketManager) listenChannel() {
for {
select {
case ca := <-m.socketsCh:
switch ca.Type {
case uch.ActionTypeCreate:
m.sockets[ca.uid] = ca.soc
m.socketsR[ca.soc] = ca.uid
break
case uch.ActionTypeDelete:
m._removeSocket(&ca)
break
}
}
}
}