Files
gocommon/wshandler/room.go

99 lines
2.0 KiB
Go
Raw Normal View History

package wshandler
import (
"context"
2023-07-11 14:30:10 +09:00
"encoding/json"
"github.com/gorilla/websocket"
"repositories.action2quare.com/ayo/gocommon/logger"
)
type room struct {
2023-07-05 22:26:57 +09:00
inChan chan *wsconn
outChan chan *wsconn
messageChan chan *UpstreamMessage
name string
destroyChan chan<- string
sendMsgChan chan<- send_msg_queue_elem
}
// 만약 destroyChan가 nil이면 room이 비어도 파괴되지 않는다. 영구 유지되는 room
func makeRoom(name string, destroyChan chan<- string, sendMsgChan chan<- send_msg_queue_elem) *room {
return &room{
2023-07-05 22:26:57 +09:00
inChan: make(chan *wsconn, 10),
outChan: make(chan *wsconn, 10),
messageChan: make(chan *UpstreamMessage, 100),
name: name,
destroyChan: destroyChan,
sendMsgChan: sendMsgChan,
}
}
func (r *room) broadcast(msg *UpstreamMessage) {
r.messageChan <- msg
}
func (r *room) in(conn *wsconn) *room {
r.inChan <- conn
return r
}
func (r *room) out(conn *wsconn) *room {
r.outChan <- conn
return r
}
func (r *room) start(ctx context.Context) {
go func(ctx context.Context) {
2023-07-05 22:26:57 +09:00
conns := make(map[string]*wsconn)
normal := false
for !normal {
normal = r.loop(ctx, &conns)
}
}(ctx)
}
2023-07-05 22:26:57 +09:00
func (r *room) loop(ctx context.Context, conns *map[string]*wsconn) (normalEnd bool) {
defer func() {
s := recover()
if s != nil {
logger.Error(s)
normalEnd = false
}
}()
2023-07-11 15:26:13 +09:00
tag := "#" + r.name
for {
select {
case <-ctx.Done():
return true
case conn := <-r.inChan:
2023-07-11 09:36:21 +09:00
(*conns)[conn.sender.Accid.Hex()] = conn
case conn := <-r.outChan:
2023-07-11 09:36:21 +09:00
delete((*conns), conn.sender.Accid.Hex())
if len(*conns) == 0 && r.destroyChan != nil {
r.destroyChan <- r.name
return true
}
case msg := <-r.messageChan:
2023-07-11 14:30:10 +09:00
ds := DownstreamMessage{
Alias: msg.Alias,
Body: msg.Body,
2023-07-11 15:26:13 +09:00
Tag: append(msg.Tag, tag),
2023-07-11 14:30:10 +09:00
}
bt, _ := json.Marshal(ds)
for _, conn := range *conns {
r.sendMsgChan <- send_msg_queue_elem{
to: conn,
mt: websocket.TextMessage,
msg: bt,
}
}
}
}
}