-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathconn.go
45 lines (40 loc) · 820 Bytes
/
conn.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
package main
import (
"github.com/alehano/wsgame/game"
"github.com/gorilla/websocket"
)
type playerConn struct {
ws *websocket.Conn
*game.Player
room *room
}
// Receive msg from ws in goroutine
func (pc *playerConn) receiver() {
for {
_, command, err := pc.ws.ReadMessage()
if err != nil {
break
}
// execute a command
pc.Command(string(command))
// update all conn
pc.room.updateAll <- true
}
pc.room.leave <- pc
pc.ws.Close()
}
func (pc *playerConn) sendState() {
go func() {
msg := pc.GetState()
err := pc.ws.WriteMessage(websocket.TextMessage, []byte(msg))
if err != nil {
pc.room.leave <- pc
pc.ws.Close()
}
}()
}
func NewPlayerConn(ws *websocket.Conn, player *game.Player, room *room) *playerConn {
pc := &playerConn{ws, player, room}
go pc.receiver()
return pc
}