-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
283 lines (251 loc) · 5.9 KB
/
server.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/websocket"
"sync"
)
type Connection struct {
sync.Mutex
playerName string
isUp bool
conn *websocket.Conn
}
func (this *Connection) send(msg []byte, msgType int){
this.Lock()
if err := this.conn.WriteMessage(msgType, msg); err != nil {
log.Println(err)
}
this.Unlock()
}
func (this *Connection) setConn(conn *websocket.Conn) {
this.conn = conn
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
var m ModelImpl
var oneConnection bool
var connections map[int]*Connection
func homePage(w http.ResponseWriter, r *http.Request){
http.ServeFile(w,r, "index.html")
}
func sendCard(path string, playerID int, msgType int){
if !m.isWatching(playerID){
path = m.getBlackPath()
}
img, _ := ioutil.ReadFile(path)
str := base64.StdEncoding.EncodeToString(img)
cardMessage := cardMsg{str}
i, _ := genericJSON(cardMessage)
connections[playerID].send(i, msgType)
}
func sendPlayers(playerID int, msgType int){
pList := m.getPlayerList()
msg, _ := genericJSON(pList)
connections[playerID].send(msg, msgType)
}
func isUp(name string) bool {
id, _ := m.getPlayerID(name)
return connections[id].isUp
}
func checkAndSendCard(player *Player, msgType int) {
//if it's the first connection, extract a card and send it
//else, send the current card
var path string
if(!oneConnection){
path = m.extractCard().getPath()
oneConnection = true
} else {
path = m.currentCard.getPath()
}
sendCard(path, player.id, msgType)
}
func handleHello(msg hello, conn *websocket.Conn, msgType int){
m.Lock()
//check if name already taken
if !(m.checkName(msg.Name)) && isUp(msg.Name) {
//TODO: handle reconnection
log.Println("Attempt to log as ", msg.Name)
ack := helloACK{
Accepted :false,
Text: "Username già in uso",
}
b, _ := genericJSON(ack)
m.Unlock();
if err := conn.WriteMessage(msgType, b); err != nil {
log.Println(err)
}
return
} else if m.existsName(msg.Name) {
if !isUp(msg.Name){
//reconnection
log.Println("Reconnecting ", msg.Name)
id, err := m.getPlayerID(msg.Name)
if err != nil {
log.Fatal("Error while retrieving player id")
}
//store new connection
connections[id].conn = conn
//prepare ack
ack := helloACK{
Accepted: true,
Text : "Bentornato, " + msg.Name,
PlayerID : id,
TeamID : m.Players[id].team.id,
}
//send ack
b, _ := genericJSON(ack)
if err := conn.WriteMessage(msgType, b); err != nil {
log.Println(err)
}
//send card
checkAndSendCard(m.Players[id], msgType)
m.Unlock()
return
}
}
//name not taken: accept player
//adds player to model
name := string(msg.Name)
player, err := m.addPlayer(name)
if err != nil {
fmt.Println("Cannot add player")
//TODO: handle this case
}
//store connection
connections[player.id] = &Connection{
playerName: name,
isUp: true,
conn: conn,
}
//send ack
ack := helloACK{
Accepted : true,
Text: "Benvenuto, " + msg.Name,
PlayerID: player.id,
TeamID: player.team.id,
}
b, _ := genericJSON(ack)
if err := conn.WriteMessage(msgType, b); err != nil {
log.Println(err)
}
//if it's the first connection, extract a card and send it
//else, send the current card
checkAndSendCard(player, msgType)
for id := range connections {
go sendPlayers(id, msgType)
}
m.Unlock()
}
func handleChangeCard(msg changeCard, conn *websocket.Conn, msgType int){
m.Lock()
if msg.PlayerID != m.currentPlayer {
log.Println("Attempt to change turn from ", msg.PlayerID, " while it's ", m.currentPlayer, " turn")
return
}
c := m.extractCard()
for playerID, conn := range connections{
if(conn.isUp) {
go sendCard(c.getPath(), playerID, msgType)
}
}
m.Unlock()
}
func handleStartTimer(msg timerStart, msgType int) {
m.Lock()
for _, c := range connections {
if c.isUp {
msg := timerStart{msg.PlayerID}
js, _ := genericJSON(msg)
c.send(js, msgType)
}
}
m.Unlock()
}
func handleEndTurn(msg endTurn, msgType int) {
m.Lock()
//new turn
m.nextTurn()
p := m.currentPlayer
//send a new turn message to all the connections
nt := newTurn{p}
toSend, _ := genericJSON(nt)
for _, c := range connections {
go func(c *Connection){
c.send(toSend, msgType)
}(c)
}
//extract a new card and send it
c := m.extractCard()
for playerID := range connections {
go func(playerID int) {
sendCard(c.getPath(), playerID, msgType)
sendPlayers(playerID, msgType) }(playerID)
}
m.Unlock()
}
func reader(conn *websocket.Conn){
for {
msgType, p, err := conn.ReadMessage()
if err != nil {
//handle disconnection
for id, c := range connections {
if c.conn == conn {
c.isUp = false
c.conn = nil
m.Players[id].connected = false
fmt.Println(m.Players[id].name, " disconnected");
break
}
}
return
}
log.Println(string(p))
msg, err := getMsg(p)
if err != nil {
fmt.Println(err)
}
switch msg.(type) {
case hello:
welcomeMsg := msg.(hello)
handleHello(welcomeMsg, conn, msgType)
case changeCard:
changeCardMsg := msg.(changeCard)
handleChangeCard(changeCardMsg, conn, msgType)
case timerStart:
startTimer := msg.(timerStart)
handleStartTimer(startTimer, msgType)
case endTurn:
endT := msg.(endTurn)
handleEndTurn(endT, msgType)
default:
log.Fatal("Unrecognized message", msg)
}
}
}
func wsEndPoint(w http.ResponseWriter, r *http.Request){
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Connection refused")
} else {
fmt.Println("Client,", r.RemoteAddr, " succesfully connected")
}
reader(ws)
}
func setupRoutes(){
http.HandleFunc("/", homePage)
http.HandleFunc("/ws", wsEndPoint)
}
func main(){
connections = make(map[int]*Connection)
m.init(2)
setupRoutes()
fmt.Println("Listening on port 12345")
log.Fatal(http.ListenAndServe(":12345", nil))
}