42 lines
1.1 KiB
Go
42 lines
1.1 KiB
Go
package server
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var player_number = 0
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
func SocketHandler(w http.ResponseWriter, r *http.Request) {
|
|
log.Println("SocketHandler invoked")
|
|
|
|
// Allow connections from any origin
|
|
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
log.Print("Error during connection upgrading:", err)
|
|
return
|
|
}
|
|
|
|
GetLobby().registerPlayer(NewPlayer(player_number, conn))
|
|
player_number = player_number + 1
|
|
}
|
|
|
|
func WriteMessageToPlayer(player *Player, msg []byte, msgType int) error {
|
|
log.Printf("Writing message: %s (with messagetype %d) to player %d", string(msg), msgType, player.id)
|
|
log.Println("")
|
|
return player.conn.WriteMessage(msgType, msg)
|
|
}
|
|
|
|
func ReadMessageFromPlayer(player *Player) (messageType int, p []byte, err error) {
|
|
msgType, msg, err := player.conn.ReadMessage()
|
|
log.Printf("Reading message: %s (with messagetype %d) from player %d", string(msg), msgType, player.id)
|
|
log.Println("")
|
|
return msgType, msg, err
|
|
}
|