Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "net/http"
- "time"
- "net/url"
- "github.com/gorilla/websocket"
- "strings"
- "strconv"
- )
- var (
- //Pass connections between threads
- conchan chan *websocket.Conn
- //Master quit channel (not implemented)
- quit chan int16
- //Base HTTP server for websocket upgrade
- serv = &http.Server{Addr: "localhost:3000", ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second}
- //Upgrader
- wsupgr = websocket.Upgrader{CheckOrigin: checkReq}
- //Shows how many users are
- // [0] - in the lobby
- // [1] - being matched
- // [2] - in game
- states = []uint64{0, 0, 0}
- )
- //Makes shure the origin of the request is not compromised
- func checkReq(r *http.Request) bool{
- u, err := url.Parse(r.Header["Origin"][0])
- if err != nil {
- return false
- }
- return strings.HasPrefix(r.Host, u.Host)
- }
- //Accepts a http request, translates it to a websocket, and passes it into the rest of the code
- func hndl(w http.ResponseWriter, r *http.Request) {
- c, err := wsupgr.Upgrade(w, r, nil)
- if err != nil {
- fmt.Println("[ERR]", err)
- return
- }
- lobby(c)
- }
- //Returns a string representation of [states]
- func getUsers() string {
- return fmt.Sprintf("%s:%s:%s", strconv.FormatUint(states[0]), strconv.FormatUint(states[1]), strconv.FormatUint(states[2]))
- }
- //Accepts a websocket connection and performs basic tasks
- func lobby(conn *websocket.Conn){
- states[0]++
- fmt.Println("In Lobby")
- conn.WriteJSON(DataJSON{"lobby", ""})
- var dat DataJSON
- for {
- err := conn.ReadJSON(&dat)
- if err != nil {
- states[0]--
- fmt.Println("[ALERT]", err)
- conn.Close()
- return
- }
- switch dat.Data{
- case "match":
- fmt.Println("Matching")
- conn.WriteJSON(DataJSON{"matching", ""})
- conchan <- conn
- return
- case "state":
- fmt.Println("State")
- conn.WriteJSON(DataJSON{"matching", getUsers()})
- default:
- break
- }
- }
- }
- //Starting point for program
- func main() {
- conchan = make(chan *websocket.Conn)
- quit = make(chan int16)
- go grouper(conchan, quit)
- http.HandleFunc("/lobby", hndl)
- fmt.Println("Error: ", serv.ListenAndServe())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement