-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.go
104 lines (89 loc) · 2.12 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
package main
import (
"log"
"net/http"
"sync"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/pborman/uuid"
)
type player struct {
Y int // Y position of the player
X int // X position
ID string // a unique id to identify the player by the frontend
Online bool
socket *websocket.Conn // websocket connection of the player
}
var players = make(map[string]*player)
var mutex sync.RWMutex
func remoteHandler(res http.ResponseWriter, req *http.Request) {
var err error
//when someone requires a ws connection we create a new player and store a
// pointer to the connection inside player.Socket
ws, err := websocket.Upgrade(res, req, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(res, "not a websocket handshake", 400)
return
} else if err != nil {
log.Println(err)
return
}
log.Printf("got websocket conn from %v\n", ws.RemoteAddr())
id := uuid.New()
player := new(player)
player.socket = ws
player.ID = id
player.Online = true
mutex.Lock()
players[id] = player
mutex.Unlock()
mutex.RLock()
for k := range players {
if k != player.ID {
if err = player.socket.WriteJSON(players[k]); err != nil {
log.Println(err)
}
}
}
mutex.RUnlock()
go func() {
for {
if err = player.socket.ReadJSON(&player); err != nil {
log.Println("player Disconnected waiting", err)
disconnectHandler(player)
return
}
mutex.RLock()
for k := range players {
if k != player.ID {
if err = players[k].socket.WriteJSON(player); err != nil {
log.Println(err)
}
}
}
mutex.RUnlock()
}
}()
}
func disconnectHandler(p *player) {
p.Online = false
mutex.RLock()
for k := range players {
if k != p.ID {
if err := players[k].socket.WriteJSON(p); err != nil {
log.Println(err)
}
}
}
mutex.RUnlock()
mutex.Lock()
delete(players, p.ID)
mutex.Unlock()
log.Println("number of players still connected ...", len(players))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/ws", remoteHandler)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
http.ListenAndServe(":3000", r)
}