implement subscribe_mp_complete_match

This commit is contained in:
Morgan Bazalgette 2017-08-09 12:46:50 +02:00
parent 6925ce4c6e
commit b7c00722de
No known key found for this signature in database
GPG Key ID: 40D328300D245DA5
3 changed files with 84 additions and 13 deletions

View File

@ -72,6 +72,7 @@ func (c *conn) WriteJSON(t string, data interface{}) error {
var messageHandler = map[string]func(c *conn, message incomingMessage){
TypeSubscribeScores: SubscribeScores,
TypeSubscribeMultiMatches: SubscribeMultiMatches,
TypeSetRestrictedVisibility: SetRestrictedVisibility,
TypeIdentify: Identify,
TypePing: pingHandler,
@ -85,6 +86,8 @@ const (
TypeNotFound = "not_found"
TypeSubscribedToScores = "subscribed_to_scores"
TypeNewScore = "new_score"
TypeSubscribedToMultiMatches = "subscribed_mp_complete_match"
TypeNewMatch = "new_completed_match"
TypeIdentified = "identified"
TypeRestrictedVisibilitySet = "restricted_visibility_set"
TypePong = "pong"
@ -93,6 +96,7 @@ const (
// Client Message Types
const (
TypeSubscribeScores = "subscribe_scores"
TypeSubscribeMultiMatches = "subscribe_mp_complete_match"
TypeIdentify = "identify"
TypeSetRestrictedVisibility = "set_restricted_visibility"
TypePing = "ping"

57
app/websockets/multi.go Normal file
View File

@ -0,0 +1,57 @@
package websockets
import (
"encoding/json"
"fmt"
"sync"
)
// SubscribeMultiMatches subscribes to receiving information from completed
// games in multiplayer matches.
func SubscribeMultiMatches(c *conn, message incomingMessage) {
multiSubscriptionsMtx.Lock()
var found bool
for _, el := range multiSubscriptions {
if el.ID == c.ID {
found = true
break
}
}
// if it was not found, we need to add it
if !found {
multiSubscriptions = append(multiSubscriptions, c)
}
multiSubscriptionsMtx.Unlock()
c.WriteJSON(TypeSubscribedToMultiMatches, nil)
}
var multiSubscriptions []*conn
var multiSubscriptionsMtx = new(sync.RWMutex)
func matchRetriever() {
ps, err := red.Subscribe("api:mp_complete_match")
if err != nil {
fmt.Println(err)
}
for {
msg, err := ps.ReceiveMessage()
if err != nil {
fmt.Println(err.Error())
return
}
go handleNewMultiGame(msg.Payload)
}
}
func handleNewMultiGame(payload string) {
defer catchPanic()
multiSubscriptionsMtx.RLock()
cp := make([]*conn, len(multiSubscriptions))
copy(cp, multiSubscriptions)
multiSubscriptionsMtx.RUnlock()
for _, el := range cp {
el.WriteJSON(TypeNewMatch, json.RawMessage(payload))
}
}

View File

@ -16,6 +16,7 @@ func Start(r *redis.Client, _db *sqlx.DB) error {
red = r
db = _db
go scoreRetriever()
go matchRetriever()
return nil
}
@ -29,4 +30,13 @@ func cleanup(connID uint64) {
}
}
scoreSubscriptionsMtx.Unlock()
multiSubscriptionsMtx.Lock()
for idx, el := range multiSubscriptions {
if el.ID == connID {
multiSubscriptions[idx] = multiSubscriptions[len(multiSubscriptions)-1]
multiSubscriptions = multiSubscriptions[:len(multiSubscriptions)-1]
break
}
}
multiSubscriptionsMtx.Unlock()
}