Skip to content

YofaGh/Cards

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

170 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Card Games Server

A high-performance, real-time multiplayer card game server built in Rust, supporting traditional Persian card games with modern networking capabilities.

Overview

This server provides a complete backend infrastructure for hosting multiplayer card games with real-time communication, player matchmaking, friend systems, and comprehensive game state management. The architecture is designed for scalability, reliability, and low-latency gameplay experiences.

Clients

Two clients are available for this server:

Supported Games

  • Qafoon - A 4-player trick-taking game with bidding mechanics (supports parties)
  • Dirty Seven - A 3-7 player shedding-type card game (solo play only)

Core Technologies

Backend Framework & Runtime

  • Rust - Systems programming language for performance and safety
  • Tokio - Asynchronous runtime for concurrent operations
  • Axum - Modern web framework for REST API endpoints

Networking & Protocols

  • TCP - Raw TCP sockets for low-latency game communication
  • WebSocket - WebSocket protocol for browser-based clients
  • TLS/SSL - Encrypted connections via Tokio-Rustls
  • MessagePack - Binary serialization for efficient data transfer

Database & Persistence

  • PostgreSQL - Relational database for user data and game statistics
  • SQLx - Type-safe SQL with compile-time query verification
  • Database Migrations - Schema versioning and management

Authentication & Security

  • JWT - Token-based authentication with configurable expiration
  • Bcrypt - Secure password hashing
  • Input Validation - Comprehensive request validation

Real-time Systems

  • Event-Driven Architecture - Broadcast channels for game events
  • Player Reconnection - Automatic reconnection with state preservation
  • Message Queuing - Pending message handling for disconnected players

Architecture

Server Components

  • API Server - RESTful endpoints for authentication, game management, and friend operations
  • Game Server - Real-time game logic and state management (TCP + WebSocket)
  • Social Server - Friend system, parties, and social interactions (TCP + WebSocket)

Key Features

Game Management

  • Queue System - Automatic matchmaking with timeout mechanisms
  • Party Support - Create and join games with friends (game-dependent)
  • Reconnection - Seamless reconnection with state recovery
  • Game State Persistence - Complete game state tracking and history

Social Features

  • Friend System - Send, accept, and manage friend requests
  • Friend Status - Real-time online/offline/in-game status tracking
  • Player Search - Search users by username
  • Block System - Block and unblock users
  • Party System - Create parties, invite friends, and queue together

Player Features

  • Multiple Protocol Support - Connect via TCP or WebSocket
  • Secure Connections - Optional TLS encryption
  • Session Management - Token-based session handling
  • Game Statistics - Track wins, games played, and rankings

Network Protocol

The server uses a custom binary protocol over TCP/WebSocket with MessagePack serialization:

  • Handshake - Initial connection establishment
  • Authentication - JWT token verification
  • Message Exchange - Length-prefixed binary messages
  • Graceful Shutdown - Proper connection cleanup

Supported Connection Types

  • Plain TCP (development)
  • TLS-encrypted TCP (production)
  • Plain WebSocket (development)
  • WSS (WebSocket Secure) (production)

Configuration

The server is configured via environment variables:

# Game Server
GAME_SERVER_HOST=0.0.0.0
GAME_SERVER_PORT=12345
GAME_SERVER_WS_PORT=12346

# Social Server
SOCIAL_SERVER_HOST=0.0.0.0
SOCIAL_SERVER_PORT=12347
SOCIAL_SERVER_WS_PORT=12348

# API Server
API_SERVER_HOST=0.0.0.0
API_SERVER_PORT=8081

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/cards_game
DATABASE_MAX_CONNECTIONS=10
DATABASE_MIN_CONNECTIONS=2

# Security
JWT_SECRET=your_secret_key
JWT_EXPIRE_DURATION=24

# TlS Configuration
TLS_ENABLED="true"
TLS_CERTS_PATH="."

# Timeouts
PLAYER_CHOICE_TIMEOUT=30
QUEUE_CUTOFF_TIMEOUT=600
GAME_DURATION_TIMEOUT=10800
PLAYER_RECONNECTION_TIMEOUT=60

Game Logic

Qafoon (4 Players, Team-based)

  • Betting phase with highest bidder selection
  • Trump (Hokm) selection with special variants (Naras, Saras, Tak Naras)
  • Trick-taking gameplay with team scoring
  • Target score: 104 points

Dirty Seven (3-7 Players, Solo)

  • Special card effects (2, 7, 8, Jack, Ace)
  • Dynamic card drawing and playing
  • Rotation changes and player skipping
  • Last player standing loses

API Endpoints

Authentication

  • POST /auth/register - Create new account
  • POST /auth/login - User login
  • POST /auth/admin/login - Admin login

API Game Management

  • GET /games/available - List available games
  • POST /games/join - Join game queue
  • GET /games/session/status - Check current session
  • DELETE /games/session/leave - Leave current session

Friends

  • POST /friends/request/{friend_id} - Send friend request
  • POST /friends/request/{requester_id}/accept - Accept request
  • GET /friends - List friends
  • GET /friends/requests/pending - Pending requests
  • DELETE /friends/{friend_id} - Remove friend
  • POST /friends/block/{user_id} - Block user

Social

  • GET /social/join - Join social server

Admin (Protected)

  • GET /admin/users/{id} - Get user details
  • POST /admin/users/{id}/lock - Lock user account
  • POST /admin/users/{id}/unlock - Unlock user account
  • DELETE /admin/users/{id} - Delete user account

Development

Prerequisites

  • Rust 1.70+
  • PostgreSQL 14+
  • OpenSSL development libraries

Building

cargo build --release

Running

# Run migrations
sqlx migrate run

# Start server
cargo run --release

Development Mode with Self-Signed Certs

cargo run --features dev-certs

Logging & Monitoring

  • Structured Logging - JSON-formatted logs with tracing
  • Log Rotation - Daily rotating log files
  • Request Tracing - Full request/response tracing
  • Performance Metrics - Connection and game event tracking

Security Features

  • Password validation (minimum 8 characters, uppercase, lowercase, digit)
  • Email validation
  • Username validation (3-50 characters, alphanumeric + _ -)
  • Rate limiting on sensitive endpoints
  • SQL injection protection via prepared statements
  • Token expiration and refresh
  • Account locking mechanisms

Error Handling

Comprehensive error types covering:

  • Network errors (TCP, TLS, timeouts)
  • Game logic errors (invalid moves, state violations)
  • Database errors (connection, query failures)
  • Authentication errors (invalid tokens, expired sessions)
  • Validation errors (malformed input)

License

This project is proprietary software. All rights reserved.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages