Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

50 Commits

Folders and files

Repository files navigation

GameServer - WebSocket Game Server

A Real-time game server built with .NET 8 using raw System.Net.WebSockets.

This project demonstrates a production-ready approach to low-level socket communication, intentionally avoiding high-level abstractions like SignalR to showcase a custom, extensible message-routing architecture. Following Clean Architecture principles, the solution is designed for high maintainability and testability, featuring a decoupled domain layer, thread-safe session management, and atomic state persistence using SQLite with EF Core.

Architecture

Clean Architecture Layers

graph TB
    subgraph API["🌐 GameServer.Api"]
        WS[WebSocket Middleware]
        MD[Message Dispatcher]
    end

    subgraph APP["βš™οΈ GameServer.Application"]
        LH[LoginHandler]
        RH[ResourceHandler]
        GH[GiftHandler]
        AH[AddFriendHandler]
    end

    subgraph INFRA["πŸ”§ GameServer.Infrastructure"]
        SM[SessionManager<br/>In-Memory]
        GN[GameNotifier<br/>WebSocket]
        SR[StateRepository<br/>SQLite/EF Core]
        SP[SyncProvider<br/>Semaphores]
    end

    subgraph DOMAIN["πŸ“¦ GameServer.Domain"]
        P[Player]
        R[Resource]
        F[Friendship]
        RS[Result&lt;T&gt;]
    end

    WS --> MD
    MD --> LH & RH & GH & AH
    LH & RH & GH & AH --> SM & GN & SR & SP
    SM & GN & SR --> P & R & F & RS

    style API fill:#4a9eff,color:#fff
    style APP fill:#50c878,color:#fff
    style INFRA fill:#ff9f43,color:#fff
    style DOMAIN fill:#a55eea,color:#fff
Loading

Message Flow

sequenceDiagram
    participant C as πŸ“± Client
    participant WS as WebSocket Middleware
    participant D as Message Dispatcher
    participant H as Handler
    participant DB as SQLite
    participant N as Notifier

    C->>WS: Connect (ws://...)
    WS-->>C: Connection Accepted

    C->>WS: {"type": "LOGIN", "payload": {...}}
    WS->>D: Dispatch Message
    D->>H: LoginHandler.HandleAsync()
    H->>DB: CreatePlayer / GetPlayer
    DB-->>H: Player ID
    H->>N: SendToPlayerAsync()
    N-->>C: {"type": "LOGIN_RESPONSE", "payload": {...}}

    Note over C,N: Player is now authenticated

    C->>WS: {"type": "SEND_GIFT", "payload": {...}}
    WS->>D: Dispatch Message
    D->>H: GiftHandler.HandleAsync()
    H->>DB: Transfer Resources (Transaction)
    H->>N: Notify Recipient
    N-->>C: 🎁 GIFT_RECEIVED
Loading

Data Model

erDiagram
    PLAYER {
        Guid Id PK
        string DeviceId UK
        DateTime LastLogin
    }

    RESOURCE {
        Guid PlayerId FK
        int Type PK
        long Amount
    }

    FRIENDSHIP {
        Guid PlayerId1 PK,FK
        Guid PlayerId2 PK,FK
        DateTime CreatedAt
    }

    PLAYER ||--o{ RESOURCE : has
    PLAYER ||--o{ FRIENDSHIP : friends
Loading

Prerequisites

Quick Start

# Clone and restore
git clone https://github.com/yakov10105/GameServer.git
dotnet restore

# Terminal 1: Run the server
dotnet run --project src/GameServer.Api

# Terminal 2: Run the client (run it twice in different terminals to test communication between players)
dotnet run --project src/GameServer.ConsoleClient

Run Tests

dotnet test

Log Files: Both Backend and Console-Client logs are saved to the logs/ directory with daily rolling files:

logs/api/api-log-20260113.log
logs/client/console-client-20260111.log
...

Protocol

All messages use a JSON envelope format:

{
  "type": "MESSAGE_TYPE",
  "payload": { ... }
}

Message Types

Type Direction Description
LOGIN Client β†’ Server Authenticate with device ID
LOGIN_RESPONSE Server β†’ Client Returns player ID
UPDATE_RESOURCES Client β†’ Server Add/deduct coins or rolls
RESOURCE_UPDATED Server β†’ Client Returns new balance after update
ADD_FRIEND Client β†’ Server Add another player as friend
SEND_GIFT Client β†’ Server Send resources to a friend
FRIEND_ADDED Server β†’ Client Notification when added as friend
FRIEND_ONLINE Server β†’ Client Notification when a friend comes online
GIFT_RECEIVED Server β†’ Client Notification of received gift
ERROR Server β†’ Client Error response

Example: Login

Request:

{
  "type": "LOGIN",
  "payload": { "deviceId": "my-device-123" }
}

Response:

{
  "type": "LOGIN_RESPONSE",
  "payload": { "playerId": "550e8400-e29b-41d4-a716-446655440000" }
}

Client Commands

login [device-id]              Login (auto-generates ID if omitted)
balance <type> <value>         Update resource (0=Coins, 1=Rolls)
addfriend <player-id>          Add a player as friend
gift <friend-id> <type> <amt>  Send gift to friend
help                           Show commands
quit                           Disconnect and exit

Testing Gift Flow

To test the complete gift flow between two players, open 3 terminals:

# Terminal 1: Start the API server
dotnet run --project src/GameServer.Api

# Terminal 2: Client A
dotnet run --project src/GameServer.ConsoleClient

# Terminal 3: Client B
dotnet run --project src/GameServer.ConsoleClient

Test Steps

# Client A: Login
> login
βœ“ Logged in! PlayerId: 11111111-aaaa-bbbb-cccc-dddddddddddd

# Client B: Login
> login
βœ“ Logged in! PlayerId: 22222222-eeee-ffff-0000-111111111111

# Client A: Add coins to have something to gift
> balance 0 500
πŸ’° Balance updated! Coins: 500

# Client A: Add Client B as friend (copy B's PlayerId)
> addfriend 22222222-eeee-ffff-0000-111111111111

# Client B should see:
πŸ‘‹ New friend! Player 11111111-aaaa-bbbb-cccc-dddddddddddd added you as a friend.

# Client A: Send gift to Client B
> gift 22222222-eeee-ffff-0000-111111111111 0 100
Sending 100 Coins...

# Client B should see:
🎁 Gift received! From: 11111111-aaaa-bbbb-cccc-dddddddddddd, Type: Coins, Amount: 100

Important: Players must be friends before sending gifts!

Project Structure

graph LR
    subgraph src[πŸ“ src]
        API[GameServer.Api]
        APP[GameServer.Application]
        INFRA[GameServer.Infrastructure]
        DOM[GameServer.Domain]
        CLI[GameServer.ConsoleClient]
    end

    subgraph tests[πŸ“ tests]
        UT[GameServer.UnitTests]
    end

    API --> APP
    API --> INFRA
    APP --> DOM
    INFRA --> DOM
    CLI -.-> API
    UT -.-> API & APP & INFRA & DOM

    style DOM fill:#a55eea,color:#fff
    style APP fill:#50c878,color:#fff
    style INFRA fill:#ff9f43,color:#fff
    style API fill:#4a9eff,color:#fff
    style CLI fill:#fd79a8,color:#fff
Loading
Project Description
GameServer.Domain Entities, interfaces, Result<T>, enums
GameServer.Application Message handlers, business logic, DTOs
GameServer.Infrastructure EF Core, SQLite, session management, WebSocket notifier
GameServer.Api WebSocket middleware, DI configuration, entry point
GameServer.ConsoleClient Interactive CLI client for testing
GameServer.UnitTests xUnit + Moq unit tests

Key Features

  • Raw WebSockets: No SignalR, pure System.Net.WebSockets
  • Clean Architecture: Domain β†’ Application β†’ Infrastructure β†’ API
  • Security: Player ID derived from WebSocket context, never from payload
  • Performance: Zero-allocation logging with [LoggerMessage] source generators
  • Concurrency: Thread-safe session management with ConcurrentDictionary
  • Transactions: Atomic gift transfers using EF Core transactions

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages