Last active
August 29, 2015 13:56
-
-
Save dpogorzelski/9298482 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, _ := websocket.Upgrade(res, req, nil, 1024, 1024) | |
log.Printf("got websocket conn from %v\n", ws.RemoteAddr()) | |
player := new(Player) | |
player.Id = uuid.New() | |
player.Socket = ws | |
// we broadcast the position of the new player to alredy connected | |
// players (if any) and viceversa, we tell the player where to spawn already | |
// existing players | |
log.Println("Publishing positions") | |
for _, p := range Players { | |
if p.Socket.RemoteAddr() != player.Socket.RemoteAddr() { | |
player.Socket.WriteJSON(p.position(true)) | |
p.Socket.WriteJSON(player.position(true)) | |
} | |
} | |
// we append the new player to Players slice | |
Players = append(Players, player) | |
for { | |
// if a network error occurs (aka someone closed the game) we let | |
// the other players know to despawn his sprite (Online: false) and | |
// remove him from the slice so no further updates will be sent | |
if err = player.Socket.ReadJSON(&player); err != nil { | |
log.Println("Player Disconnected waiting", err.Error()) | |
for i, p := range Players { | |
if p.Socket.RemoteAddr() == player.Socket.RemoteAddr() { | |
Players = append(Players[:i], Players[i+1:]...) | |
} else { | |
log.Println("destroy player", player) | |
p.Socket.WriteJSON(Message{Online: false, Id: player.Id}) | |
} | |
} | |
log.Println("Number of players still connected ...", len(Players)) | |
return | |
} | |
// a regular broadcast to inform all the players about a player's | |
// position update | |
for _, p := range Players { | |
if p.Socket.RemoteAddr() != player.Socket.RemoteAddr() { | |
p.Socket.WriteJSON(player.position(false)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment