# Websockets

{% hint style="warning" %}
**Warning**: This module must be attached to an existing **Node.js** server, either the template we provide or a custom project from the user. However, it can only be attached to the **Premium** template due to the use of **NestJS** and **TypeScript**. If you already own the HTTPS Premium module, you can refer to the README to include only the necessary files and be guided on how to make calls to the WebSocket module.
{% endhint %}

**This module provides WebSocket functionality, designed to be integrated into an existing Node.js server. It enables real-time, bidirectional communication without providing a full server setup.**

Here are the key features and details of this module:

* **Real-Time Communication**: This module enables real-time, bidirectional communication between clients and the server using WebSockets, ideal for chat applications, live notifications, and interactive features.
* **Authentication with JWT**: Integrates JSON Web Tokens (JWT) for secure authentication, ensuring that only authorized users can establish WebSocket connections and access routes.
* **Database Integration Support**: While this module doesn't include direct database management, it can be easily integrated with any existing Node.js database setup, including those using Primsa ORM, to perform real-time data operations and keep client data synchronized.
* **CORS Management**: Allows easy handling of Cross-Origin Resource Sharing (CORS) for managing cross-origin WebSocket connections securely and ensuring proper access control.
* **Premium Features**: Designed for developers who need robust WebSocket functionality to enable real-time features within their Node.js applications, this module provides essential and advanced tools for building interactive applications.
* **Customizable and Extendable**: The module is flexible, allowing developers to modify and extend it to fit their specific project needs. It provides a strong foundation for adding real-time features and secure WebSocket connections to your application.
* **Available for Purchase**: This premium module is available for purchase, offering advanced real-time capabilities to enhance the interactivity and performance of your Node.js applications.

***

### Placement in the Project

This module should be placed in the following directory within the premium template project:

```
src/modules/websockets
```

### Installation

To get started, ensure you have the necessary dependencies installed:

```
npm install
```

If **Socket.IO** is not yet installed, run the following command:

```
npm install socket.io @nestjs/websockets @nestjs/platform-socket.io
```

### WebSocket Routes (Example)

The module comes with pre-defined WebSocket routes that demonstrate the functionality. These routes are for **example purposes** and can be modified or extended as per your project’s requirements.

#### Available WebSocket Routes:

**1. `message`**

* **Description:** Handles sending messages from a client and broadcasting them to all connected clients.
* **Payload Example:** `{ "content": "Hello World" }`

**2. `joinRoom`**

* **Description:** Allows a client to join a specified room.
* **Payload Example:** `{ "room": "room1" }`

**3. `leaveRoom`**

* **Description:** Allows a client to leave a specified room.
* **Payload Example:** `{ "room": "room1" }`

**4. `getClientsCount`**

* **Description:** Retrieves the number of currently connected clients.
* **Payload Example:** No payload is required for this route.

***

### Testing WebSocket Integration on Unity with C\#

You can easily test the WebSocket routes by using any WebSocket client, such as **Socket.IO** client, **Postman** for WebSocket, or a custom client in **Unity** or another frontend platform.

**Example Client Integration (using Socket.IO):**

```csharp
using UnityEngine;
using SocketIOClient; // Ensure you have added the Socket.IO library for C# (via NuGet or Asset Store)

public class WebSocketClient : MonoBehaviour
{
    private SocketIO client;

    void Start()
    {
        ConnectToWebSocketServer();
    }

    async void ConnectToWebSocketServer()
    {
        // Initialize the client and connect to the WebSocket server
        client = new SocketIO("http://localhost:3000");

        // Setup event handlers
        client.OnConnected += async (sender, e) =>
        {
            Debug.Log("Connected to WebSocket server");

            // Sending a message to the server
            await client.EmitAsync("message", new { content = "Hello from client!" });

            // Joining a room
            await client.EmitAsync("joinRoom", new { room = "room1" });

            // Requesting client count
            await client.EmitAsync("getClientsCount");
        };

        // Handle incoming messages from the server
        client.On("message", response =>
        {
            Debug.Log("Message from server: " + response);
        });

        // Handle client count response
        client.On("clientsCount", response =>
        {
            Debug.Log("Connected clients count: " + response.GetValue<int>("count"));
        });

        // Handle connection errors
        client.OnError += (sender, e) =>
        {
            Debug.LogError("WebSocket error: " + e.Message);
        };

        // Start the client connection
        await client.ConnectAsync();
    }

    private void OnApplicationQuit()
    {
        client?.Dispose();
    }
}
```

### Configuring for Unity

* Add the **Socket.IO** C# library to your Unity project. This can be done using a package manager like **NuGet** or by downloading the library from the **Unity Asset Store**.
* Integrate the WebSocket client script into your game object.

### Extending the WebSocket Module

The WebSocket module is designed to be modular and can be extended as needed. It includes gateways and services that handle client connections, messages, and room management:

* **ClientManagementGateway:** Handles connection and disconnection of clients.
* **RoomGateway:** Manages client membership in rooms.
* **MessageGateway:** Handles messages sent by clients and broadcasts them to all connected clients.

You can easily extend or modify these services to suit your project’s specific needs.
