Skip to content
This repository has been archived by the owner on Oct 30, 2022. It is now read-only.

Commit

Permalink
room isfull and code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
roby2014 committed Mar 1, 2022
1 parent 9b927f1 commit 0ddae54
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 30 deletions.
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ func setupRouter() {
router.HandleFunc("/api/playerstats/{steamid}", controller.GetPlayerStats).Methods("GET")

// create rooms and run them (TODO: database rooms integration)
for _, uid := range []uint{1, 2, 3, 4, 5} {
newRoom := websocket.NewRoom(uid)
for _, uid := range []int{1, 2, 3, 4, 5} {
newRoom := websocket.NewRoom(uid, 2)
roomRoute := fmt.Sprintf("/chat/%d", uid)
router.HandleFunc(roomRoute, newRoom.HandleWebsocket)
go newRoom.Run()
Expand Down
6 changes: 2 additions & 4 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@ type ErrorResponse struct {
ErrorMsg string
}

// ErrorResponse "constructor"
func NewAPIError(c int, m string) ErrorResponse {
return ErrorResponse{
Code: c,
ErrorMsg: m,
}
return ErrorResponse{Code: c, ErrorMsg: m}
}

// Error response in JSON format
Expand Down
1 change: 1 addition & 0 deletions websocket/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package websocket

import "github.com/gorilla/websocket"

// Client represents a... client
type Client struct {
socket *websocket.Conn
room *Room
Expand Down
12 changes: 5 additions & 7 deletions websocket/message.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package websocket

import (
"encoding/json"
)
import "encoding/json"

// Message represents a chat message
type Message struct {
Expand All @@ -11,8 +9,8 @@ type Message struct {
Created string `json:"created"`
}

// FromJSON created a new Message struct from given JSON
func FromJSON(jsonInput []byte) (message *Message) {
json.Unmarshal(jsonInput, &message)
return
// FromJSON creates a new Message struct from given JSON
func FromJSON(jsonData []byte) (message *Message) {
json.Unmarshal(jsonData, &message)
return message
}
37 changes: 22 additions & 15 deletions websocket/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import (

// Room represents a single chat room
type Room struct {
id uint
clients map[*Client]bool
forward chan []byte
join chan *Client
leave chan *Client
id int
maxplayers int
clients map[*Client]bool
forward chan []byte
join chan *Client
leave chan *Client
}

const (
Expand All @@ -25,19 +26,20 @@ var upgrader = &websocket.Upgrader{
ReadBufferSize: socketBufferSize,
WriteBufferSize: socketBufferSize,
CheckOrigin: func(r *http.Request) bool {
// TODO: change origin to frontend
// TODO: change origin to frontend url
return true
},
}

// Create a new chat room
func NewRoom(id uint) *Room {
func NewRoom(id int, maxplayers int) *Room {
return &Room{
id: id,
clients: make(map[*Client]bool),
forward: make(chan []byte),
join: make(chan *Client),
leave: make(chan *Client),
id: id,
maxplayers: maxplayers,
clients: make(map[*Client]bool),
forward: make(chan []byte),
join: make(chan *Client),
leave: make(chan *Client),
}
}

Expand Down Expand Up @@ -72,16 +74,21 @@ func (r *Room) leaveRoom(c *Client) {
// Print message to all in the current room
func (r *Room) printToChatAll(msg []byte) {
data := FromJSON(msg)
log.Printf("[room %v] %v: %v", r.id, data.Sender, data.Message)
log.Printf("[room %v] %v: %v", r.id, data.Sender, data)

for client := range r.clients {
select {
case client.send <- msg:
log.Println("client.send <- msg")
// success
default:
// not sure if this is possible
// not sure if this is possible/reachable but yeah
delete(r.clients, client)
close(client.send)
}
}
}

// Returns true if room is full
func (room *Room) IsFull() bool {
return len(room.clients) == room.maxplayers
}
13 changes: 11 additions & 2 deletions websocket/server.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
package websocket

import "net/http"
import (
"net/http"
)

// /api/rooms/{room_id} - create a client websocket, associating it with a room
func (room *Room) HandleWebsocket(w http.ResponseWriter, r *http.Request) {
// check if room is full
if room.IsFull() {
// TODO: return error
return
}

// create client socket
socket, err := upgrader.Upgrade(w, r, nil)
if err != nil {
// TODO: return error
return
}

Expand All @@ -16,7 +25,7 @@ func (room *Room) HandleWebsocket(w http.ResponseWriter, r *http.Request) {
// join the room
room.join <- client

// executed at end of this function (after goroutines stop)
// executed at end of this fn
defer func() {
room.leave <- client
}()
Expand Down

0 comments on commit 0ddae54

Please sign in to comment.