-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.go
131 lines (107 loc) · 2.48 KB
/
ws.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package wvss
import (
"fmt"
"github.com/labstack/echo"
"golang.org/x/net/websocket"
"gopkg.in/vmihailenco/msgpack.v2"
)
const (
CommandPacket int = iota
StatusPacket
)
type Packet struct {
Type int
Data interface{}
}
// Implement msgpack capable decoder
func MsgpackDecoder(msg []byte, payloadType byte, v interface{}) (err error) {
switch data := v.(type) {
case *string:
*data = string(msg)
return nil
case *[]byte:
*data = msg
return nil
}
err = msgpack.Unmarshal(msg, v)
if err == nil {
return nil
}
fmt.Println(err.Error())
return websocket.ErrNotSupported
}
// Implement msgpack capable encoder
func MsgpackEncoder(v interface{}) (msg []byte, payloadType byte, err error) {
switch data := v.(type) {
case string:
return []byte(data), websocket.TextFrame, nil
case []byte:
return data, websocket.BinaryFrame, nil
}
msg, err = msgpack.Marshal(v)
if err == nil {
return msg, websocket.BinaryFrame, err
}
return msg, websocket.UnknownFrame, err
}
// Setup custom websocket codec
var Msgpack = websocket.Codec{
MsgpackEncoder,
MsgpackDecoder,
}
var players PlayerList
func WebsocketHandler(c *echo.Context) (err error) {
ws := c.Socket()
var packet Packet
player := players.Add(ws)
// TODO: Handle user close connection
defer func() {
// On player disconnection
players.Remove(player)
}()
for {
if err = Msgpack.Receive(ws, &packet); err != nil {
return
}
if err = ReslovePacket(packet, player); err != nil {
fmt.Println(err.Error())
return
}
}
}
func ReslovePacket(packet Packet, player *Player) (err error) {
switch packet.Type {
case CommandPacket:
if player.Room != nil {
player.Room.Broadcast(&packet)
}
case StatusPacket:
// TODO: Redesign packet format
data := ConvertStatus((packet.Data).(map[interface{}]interface{}))
err = HandlePlayerStatus(player, data)
}
return
}
func HandlePlayerStatus(player *Player, status Status) (err error) {
switch status.Name {
case "Register":
player.Team = status.Value
err = Msgpack.Send(player.Conn, Packet{StatusPacket, Status{"Register", 1}})
case "Match":
matchedPlayer := FindMatch(player.Team)
if matchedPlayer != nil {
room := NewRoom(player, matchedPlayer)
room.Broadcast(&Packet{StatusPacket, Status{"Match", 1}})
} else {
err = Msgpack.Send(player.Conn, Packet{StatusPacket, Status{"Match", 0}})
}
}
return
}
func FindMatch(team int) *Player {
matches := players.UnmatchPlayer(team)
if len(matches) > 0 {
return matches[0]
}
return nil
}