-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame_server_session.go
77 lines (68 loc) · 1.53 KB
/
game_server_session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"encoding/json"
"github.com/gorilla/websocket"
"log"
"sync"
"time"
)
type GameServerSession struct {
sync.Mutex
f func(*GameServerSession, []byte)
conn *websocket.Conn
connectionTimeout time.Duration
Username string
}
func NewGameServerSession(conn *websocket.Conn, username string, t time.Duration) *GameServerSession {
return &GameServerSession{
conn: conn,
Username: username,
connectionTimeout: t,
}
}
func (gss *GameServerSession) Subscribe(f func(*GameServerSession, []byte)) {
gss.Lock()
defer gss.Unlock()
gss.f = f
}
func (gss *GameServerSession) Notify(data []byte) {
gss.Lock()
f := gss.f
gss.Unlock()
if f == nil {
return
}
f(gss, data)
}
func (gss *GameServerSession) Close() {
gss.conn.Close()
}
func (gss *GameServerSession) ListenConn() {
for {
deadline := time.Now().Add(gss.connectionTimeout)
if err := gss.conn.SetReadDeadline(deadline); err != nil {
return
}
_, data, err := gss.conn.ReadMessage()
if err != nil {
return
}
gss.Notify(data)
}
}
func (gss *GameServerSession) emit(e event) {
log.Println("emitted", gss.Username, e.Type())
m := map[string]any{
"type": e.Type(),
"value": e,
}
data, _ := json.Marshal(m)
if err := gss.conn.SetWriteDeadline(time.Now().Add(200 * time.Millisecond)); err != nil {
log.Println("failed to set write deadline", err)
return
}
if err := gss.conn.WriteMessage(websocket.TextMessage, data); err != nil {
log.Println("conn failed to WriteMessage", err)
return
}
}