# Client connections

### Overview <a href="#overview" id="overview"></a>

The **Client connection system** lets you uniquely identify users connected to the same session, find any user by their ID, spawn objects whenever a new user joins the session, and send messages between those users.

To achieve this a special **connection entity** is automatically created by the [Replication Server](https://docs.coherence.io/0.9/api-reference/replication-server) for each connected Client, including a Simulator. Those Entities are subject to a different rule set than standard Entities. **Connection entities**:

* Can't be created or destroyed by the Client - they are always Replication Server-driven
* Are global - they are replicated across Clients regardless of the in-simulation distance or [LiveQuery](https://docs.coherence.io/0.9/api-reference/network-sdk/livequery) extent

**Client connections** shine whenever there's a need to communicate something to all the connected players. Usage examples:

* Global chat
* Game state changes: game started, game ended, map changed
* Server announcements
* Server-wide leaderboard
* Server-wide events

### Enabling client connections <a href="#enabling-client-messages" id="enabling-client-messages"></a>

The global nature of **Client connection** doesn't fit all game types - for example, it rarely makes sense to keep every Client informed about the presence of all players on the server in an MMORPG (think World Of Warcraft). If this is your use case, make sure Client connections are **turned off** by default.

To enable **Client connections***,* check that *Global Query* in the [MonoBridge](https://docs.coherence.io/0.9/api-reference/network-sdk/monobridge) is turned on (it should be by default):

![MonoBridge component](https://3798176112-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZcBSvjNQZSas5L9C0K8K%2Fuploads%2FDWc7AydETYsu3HZDbxHf%2FScreenshot%202022-03-07%20at%2012.55.50.png?alt=media)

{% hint style="info" %}
Disabling *Global Query* on one Client doesn't affect other Clients, i.e. the **connection Entity** of this Client will still be visible to other Clients that have the *Global Query* turned on.
{% endhint %}

### Connection management <a href="#id-3-create-a-client-connection-prefab" id="id-3-create-a-client-connection-prefab"></a>

Most of the **Client connection** functionality is accessible through the `CoherenceMonoBridge.ClientConnections` object:

```csharp
using System.Collections.Generic;
using Coherence.Connection;
using Coherence.Toolkit;
using UnityEngine;

public class ExampleGameManager : MonoBehaviour
{
    public CoherenceMonoBridge MonoBridge;

    void Start()
    {
        // Raised whenever a new connection is made (including the local one).
        MonoBridge.ClientConnections.OnCreated += connection =>
        {
            Debug.Log($"Connection #{connection.ClientId} " +
                      $"of type {connection.Type} created.");
        };

        // Raised whenever a connection is destroyed.
        MonoBridge.ClientConnections.OnDestroyed += connection =>
        {
            Debug.Log($"Connection #{connection.ClientId} " +
                      $"of type {connection.Type} destroyed.");
        };

        // Raised when all initial connections have been synced.
        MonoBridge.ClientConnections.OnSynced += connectionManager =>
        {
            Debug.Log($"ClientConnections are now ready to be used.");
        };
    }
    
    void Update()
    {
        // IMPORTANT: All of the connection retrieving calls may return null 
        // if the connection system was not turned on, not initialized yet,
        // or simply if the connection was not found.
        
        // Specifies how many clients are in this session (room or world).
        int clientCount = MonoBridge.ClientConnections.ClientConnectionCount;
        
        // Returns connection objects for all connections in this session.
        IEnumerable<CoherenceClientConnection> allConnections
            = MonoBridge.ClientConnections.GetAll();

        // Returns all connections except for the local one.
        IEnumerable<CoherenceClientConnection> otherConnections
            = MonoBridge.ClientConnections.GetOther();

        // Returns connection object of the local user.
        CoherenceClientConnection myConnection
            = MonoBridge.ClientConnections.GetMine();

        // Returns connection object of the simulator (if one is connected).
        CoherenceClientConnection simulatorConnection
            = MonoBridge.ClientConnections.GetSimulator();

        // Retrieves a connection by its ClientID.
        CoherenceClientConnection selectedConnection
            = MonoBridge.ClientConnections.Get(myConnection.ClientId);

        // Retrieves a connection by its EntityID (warning: requires
        // connection prefab with a CoherenceSync attached).
        if (myConnection.Sync != null)
        {
            selectedConnection
                = MonoBridge.ClientConnections.Get(myConnection.Sync.EntityID);
        }

        // Specifies if this is a client or a simulator connection.
        ConnectionType connectionType = selectedConnection.Type;

        // Specifies if this is a local connection (belonging to the
        // local user).
        bool isMine = selectedConnection.IsMyConnection;

        // Returns a GameObject associated with this connection.
        // Applicable only if connection prefabs are used.
        GameObject connectionGameObject = selectedConnection.GameObject;
    }
}
```

Each connection is represented by a plain C# `CoherenceClientConnection` object. It contains all the important information about a connection - its `ClientID`, `Type`, whether it `IsMyConnection`, and a reference to the `GameObject` and Coherence `Sync` associated with it.

{% hint style="warning" %}
The `CoherenceClientConnection.ClientID` is guaranteed to not change during a connection's lifetime. However, if a Client disconnects and then connects again to the same Room/World, a new `ClientID` will be assigned (since a new connection was established).
{% endhint %}

### Connection objects

Each **Client connection** can have a *GameObject* with *CoherenceSync* automatically being spawned and associated with it. Those objects, like any other objects with *CoherenceSync*, can be used for syncing properties or sending messages, with a little twist - they are global and thus not limited by the LiveQuery extent. That makes them perfect candidates for operations like:

* Syncing global information - name, stats, tags, etc.
* Sending global messages - chat, server interaction

To enable connection objects:

#### 1. Create a client connection prefab <a href="#id-3-create-a-client-connection-prefab-2" id="id-3-create-a-client-connection-prefab-2"></a>

This step is described in detail in the [Prefab setup section](https://docs.coherence.io/0.9/get-started/prefab-setup). In short, a Prefab with a *CoherenceSync* and a custom component (`PlayerConnection` in this example) must be created and placed in a *Resources* folder:

![PlayerConnection prefab](https://gblobscdn.gitbook.com/assets%2F-MWd0ZPEK7vE9nkE0b7G%2F-MdqCDf3w4s6f3x7-nqQ%2F-MdqRCkj3rMik-vFzHRx%2FScreenshot_46.png?alt=media\&token=887e5109-e8ed-4157-a9f9-7fe897e63cff)

#### 2. Link a connection Prefab to the MonoBridge <a href="#id-4-link-the-connection-prefab-to-the-monobridge" id="id-4-link-the-connection-prefab-to-the-monobridge"></a>

For the system to know which object to create for every new Client connection, we have to link our Prefab to the *MonoBridge*. Simply drag the prefab to the *Client* field in the *MonoBridge* inspector:

![MonoBridge with linked connection prefab](https://3798176112-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZcBSvjNQZSas5L9C0K8K%2Fuploads%2FAJdIEfIj159iSoak6FBr%2FScreenshot%202022-03-07%20at%2013.00.00.png?alt=media)

From now on every new connection will be assigned an instance of this Prefab, which can be accessed through the `CoherenceClientConnection.GameObject` property.

#### Prefab selection <a href="#id-3-create-a-client-connection-prefab" id="id-3-create-a-client-connection-prefab"></a>

Note that there's a separate field for the *Simulator Connection Prefab*. It can be used to spawn a completely different object for the Simulator connection that may contain Simulator-specific commands and replicated properties. If the field is left empty, no object will be created for the Simulator connection.

The Prefab selection process can be also controlled from code using the `CoherenceMonoBridge.ClientConnections.ProvidePrefab` callback:

```csharp
using System.Collections.Generic;
using Coherence.Connection;
using Coherence.Toolkit;
using UnityEngine;

public class ExampleGameManager : MonoBehaviour
{
    public CoherenceMonoBridge MonoBridge;
    public CoherenceSync CustomConnectionPrefab;

    void Start()
    {
        MonoBridge = FindObjectOfType<CoherenceMonoBridge>();
        MonoBridge.ClientConnections.ProvidePrefab += (clientId, connectionType) =>
        {
            return CustomConnectionPrefab;
        };
    }
}
```

{% hint style="info" %}
A Prefab provided through the `ProvidePrefab` callback takes precedence over Prefabs linked in the inspector.
{% endhint %}

### Client messages <a href="#id-3-create-a-client-connection-prefab" id="id-3-create-a-client-connection-prefab"></a>

Client messages are [commands](https://docs.coherence.io/0.9/authority/commands) sent between the [*Client connection objects*](#connection-objects). Implementing Client messages is as simple as adding a new method to the component used by our **connection Prefab** and binding it in the configuration:

```csharp
public class PlayerConnection : MonoBehaviour
{
    // My chat command
    public void OnChatMessage(string message)
    {
        Debug.Log($"Received chat message: {message}");
    }
}
```

Don't forget to bind the new command:

![Binding a client message](https://3798176112-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZcBSvjNQZSas5L9C0K8K%2Fuploads%2FDGHPGRm4iuyyc03kAWj7%2FScreenshot%202021-12-23%20at%2017.12.03.png?alt=media)

Client messages can be sent using the `CoherenceClientConnection.SendClientMessage` method:

```csharp
using UnityEngine;
using Coherence;
using Coherence.Connection;
using Coherence.Toolkit;

public class PlayerConnection : MonoBehaviour
{
    void Start()
    {
        var monoBridge = FindObjectOfType<CoherenceMonoBridge>();
        CoherenceClientConnection myConnection = monoBridge.ClientConnections.GetMine();

        myConnection.SendClientMessage<PlayerConnection>(nameof(OnChatMessage),
            MessageTarget.Other, "Hello!");
    }

    // My chat command
    public void OnChatMessage(string message)
    {
        Debug.Log($"Received chat message: {message}");
    }
}
```

If the `ClientID` of the message recipient is known we can use the `CoherenceMonoBridge.ClientConnections` directly to send a client message:

```csharp
private ClientID lastClientId;

private void OnConnectionCreated(CoherenceClientConnection clientConnection)
{
    if (!clientConnection.IsMyConnection)
    {
        lastClientId = clientConnection.ClientId;
    }
}

public void SendMessageToLastConnection(string message)
{
    var monoBridge = FindObjectOfType<CoherenceMonoBridge>();
    monoBridge.ClientConnections.SendMessage<PlayerConnection>("OnChatMessage",
        lastClientId, MessageTarget.AuthorityOnly, "Hello!");
}
```
