Skip to content

Commit

Permalink
Isolate server/client on different packages.
Browse files Browse the repository at this point in the history
  • Loading branch information
marianogappa committed Jun 23, 2024
1 parent 0b65762 commit 546a0a7
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 33 deletions.
2 changes: 1 addition & 1 deletion ui.go → exampleclient/ui.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package exampleclient

import (
"encoding/json"
Expand Down
13 changes: 7 additions & 6 deletions websocket_client.go → exampleclient/websocket_client.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package main
package exampleclient

import (
"fmt"
"log"

"github.com/gorilla/websocket"
"github.com/marianogappa/truco/server"
"github.com/marianogappa/truco/truco"
"github.com/nsf/termbox-go"
)

func player(playerID int, address string) {
func Player(playerID int, address string) {
ui := NewUI()

err := termbox.Init()
Expand All @@ -26,14 +27,14 @@ func player(playerID int, address string) {
}
defer conn.Close()

if err := wsSend(conn, NewMessageHello(playerID)); err != nil {
if err := server.WsSend(conn, server.NewMessageHello(playerID)); err != nil {
log.Println(err)
return
}

lastRound := 0
for {
gameState, err := wsReadMessage[truco.GameState, MessageHeresGameState](conn, MessageTypeHeresGameState)
gameState, err := server.WsReadMessage[truco.GameState, server.MessageHeresGameState](conn, server.MessageTypeHeresGameState)
if err != nil {
log.Println(err)
return
Expand Down Expand Up @@ -68,8 +69,8 @@ func player(playerID int, address string) {
break
}

msg, _ := NewMessageAction(action)
if err := wsSend(conn, msg); err != nil {
msg, _ := server.NewMessageAction(action)
if err := server.WsSend(conn, msg); err != nil {
log.Println(err)
return
}
Expand Down
18 changes: 10 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ import (
"fmt"

"os"
)

// TODO: there's a bug that exists in most Truco games: it should be possible to throw a card and say truco at the same time
"github.com/marianogappa/truco/exampleclient"
"github.com/marianogappa/truco/server"
)

func main() {
if len(os.Args) < 2 {
fmt.Println("usage: truco server|player1|player2 [address]")
fmt.Println("Define the PORT environment variable to change the default port (8080).")
return
fmt.Println("usage: truco server")
fmt.Println("usage: truco player1|player2 [address]")
fmt.Println("Define the PORT environment variable for truco server to change the default port (8080).")
os.Exit(0)
}
port := os.Getenv("PORT")
if port == "" {
Expand All @@ -27,11 +29,11 @@ func main() {
arg := os.Args[1]
switch arg {
case "server":
serve(port)
server.New(port).Start()
case "player1":
player(0, address)
exampleclient.Player(0, address)
case "player2":
player(1, address)
exampleclient.Player(1, address)
default:
fmt.Println("Invalid argument. Please provide either server or client.")
}
Expand Down
10 changes: 5 additions & 5 deletions websocket_common.go → server/websocket_common.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package server

import (
"encoding/json"
Expand All @@ -8,7 +8,7 @@ import (
"github.com/gorilla/websocket"
)

func wsSend(conn *websocket.Conn, message any) error {
func WsSend(conn *websocket.Conn, message any) error {
bs, err := json.Marshal(message)
if err != nil {
log.Printf("Failed to marshal message: %v", err)
Expand All @@ -19,18 +19,18 @@ func wsSend(conn *websocket.Conn, message any) error {
return err
}

func wsReadMessage[U any, T IWebsocketMessage[U]](conn *websocket.Conn, expectedType int) (*U, error) {
func WsReadMessage[U any, T IWebsocketMessage[U]](conn *websocket.Conn, expectedType int) (*U, error) {
messageType, message, err := conn.ReadMessage()
if messageType != websocket.TextMessage {
return nil, fmt.Errorf("Expected text message, got %d", messageType)
}
if err != nil {
return nil, fmt.Errorf("Failed to read message from client: %v", err)
}
return wsDeserializeMessage[U, T](message, expectedType)
return WsDeserializeMessage[U, T](message, expectedType)
}

func wsDeserializeMessage[U any, T IWebsocketMessage[U]](message []byte, expectedType int) (*U, error) {
func WsDeserializeMessage[U any, T IWebsocketMessage[U]](message []byte, expectedType int) (*U, error) {
var m T
if err := json.Unmarshal(message, &m); err != nil {
return nil, fmt.Errorf("Failed to unmarshal message: %v", err)
Expand Down
2 changes: 1 addition & 1 deletion websocket_messages.go → server/websocket_messages.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package server

import (
"encoding/json"
Expand Down
19 changes: 7 additions & 12 deletions websocket_server.go → server/websocket_server.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package server

import (
"encoding/json"
Expand All @@ -10,25 +10,20 @@ import (
"github.com/marianogappa/truco/truco"
)

// Define WebSocket upgrader
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}

func serve(port string) {
NewServer(port).Start()
}

// TODO: resources shouldn't be shared between goroutines! It's not panicking due to insufficient testing for now.
type server struct {
gameState *truco.GameState
port string
players []*websocket.Conn
}

func NewServer(port string) *server {
func New(port string) *server {
return &server{gameState: truco.New(), port: port, players: []*websocket.Conn{nil, nil}}
}

Expand All @@ -48,7 +43,7 @@ func (s *server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
}
defer conn.Close()

playerID, err := wsReadMessage[int, MessageHello](conn, MessageTypeHello)
playerID, err := WsReadMessage[int, MessageHello](conn, MessageTypeHello)
if err != nil {
log.Println(err)
return
Expand All @@ -65,7 +60,7 @@ func (s *server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
s.players[*playerID] = conn

msg, _ := NewMessageHeresGameState(*s.gameState)
if err := wsSend(conn, msg); err != nil {
if err := WsSend(conn, msg); err != nil {
log.Println(err)
return
}
Expand All @@ -89,7 +84,7 @@ func (s *server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
switch wsMessage.Type {
case MessageTypeAction:
log.Println("Got action message:", string(message))
action, err := wsDeserializeMessage[truco.Action, MessageAction](message, MessageTypeAction)
action, err := WsDeserializeMessage[truco.Action, MessageAction](message, MessageTypeAction)
if err != nil {
log.Println(err)
return
Expand All @@ -106,7 +101,7 @@ func (s *server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
msg, _ := NewMessageHeresGameState(*s.gameState)
for i, playerConn := range s.players {
log.Println("Sending game state to player", i)
if err := wsSend(playerConn, msg); err != nil {
if err := WsSend(playerConn, msg); err != nil {
log.Println(err)
return
}
Expand All @@ -115,7 +110,7 @@ func (s *server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
log.Println("Got state request message:", string(message))

msg, _ := NewMessageHeresGameState(*s.gameState)
if err := wsSend(conn, msg); err != nil {
if err := WsSend(conn, msg); err != nil {
log.Println(err)
return
}
Expand Down

0 comments on commit 546a0a7

Please sign in to comment.