# SNetwork

**الأعضاء** 9

|       |                                                                     |                                                                                                              |
| ----- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| دالة  | [SendNetworkMessage](#sendnetworkmessage)                           | Sends a networked message to every client with a subscriber listening on 'key'.                              |
| دالة  | [SendNetworkMessageToUser](#sendnetworkmessagetouser)               | Sends a networked message to a specific user (userID) with a subscriber listening on 'key'.                  |
| دالة  | [SubscribeToRegionPropertyUpdate](#subscribetoregionpropertyupdate) | Subscribes to region property updates on 'key'.                                                              |
| دالة  | [SubscribeToNetwork](#subscribetonetwork)                           | Subscribes to network messages on 'key', will fire a SNetworkMessage whenever a matching message is received |
| دالة  | [SetRegionProperty](#setregionproperty)                             | Stores a key/value pair in the Regions semi-permanent memory.                                                |
| دالة  | [GetRegionProperty](#getregionproperty)                             | Retrieves the last set value for 'key' in this region.                                                       |
| دالة  | [SetShardProperty](#setshardproperty)                               | Sets a property named 'key' of the Shard to 'value'.                                                         |
| دالة  | [GetShardProperty](#getshardproperty)                               | Gets a previously set key.                                                                                   |
| خاصية | [HasShardProperties](#hasshardproperties)                           | Returns True upon successful connection to the Region/Shard properties' storage.                             |

## Overview

* Local network messages (region/shard scope)

  * Use SendNetworkMessage / SubscribeToNetwork with a string key.
  * Delivery is confined to the current region or shard and only to active subscribers of that key.
  * Payload is a Lua Table (dictionary) of network-serializable types. Messages are ephemeral and not stored.

* Region/Shard properties (server-stored)

  * Use SetRegionProperty/GetRegionProperty for region-scoped semi-permanent storage (persists while the region is open).
  * Use SetShardProperty/GetShardProperty for shard-scoped storage (persists until the shard shuts down or all users leave).
  * Values are strings; operations may be rate-limited and may not be immediately available on join. Use HasShardProperties to detect readiness.

## الدوال

### SendNetworkMessage

void SendNetworkMessage(string key, Table message)

void SendNetworkMessage(string key, Table message, bool serverOnly)

void SendNetworkMessage(string key, Table message, bool serverOnly, bool loopback)

Sends a networked message to every client with a subscriber listening on 'key'. The message itself can be a table/dictionary of network-serializable types (string, float, int, byte, bool and arrays of those types). Requests may be rate limited.

المعاملات

| المعامل    | النوع  | الوصف                                                          |
| ---------- | ------ | -------------------------------------------------------------- |
| key        | string | Subscription key to route the message to listeners             |
| message    | Table  | Table/dictionary of serializable values                        |
| serverOnly | bool   | Optional. If true, send via server only                        |
| loopback   | bool   | Optional. If true, also invoke local subscriber on this client |

القيم المرجعة

`void`

مثال

**Lua**

```lua
Space.Network.SendNetworkMessage('AKey', {first = "xyz", second= "abc"})
--or
Space.Network.SendNetworkMessage('AKey', {first = "xyz", second= "abc"}, true)
--or
Space.Network.SendNetworkMessage('AKey', {first = "xyz", second= "abc"}, true, true)

```

**Lua**

```lua
image = "mrlee.jpg"
server = "https://middleware.systems/"
obj = Space.Host.GetReference("Gino")

Space.Network.SubscribeToNetwork("smack", onSmack)

function hithere()

  resrc = Space.WebServices.GetImage(server .. image)
  obj.Renderer.Material.SetTexture("_MainTex", resrc)
  Space.Network.SendNetworkMessage("smack",{'smack'})
end

function update()

  resrc = Space.WebServices.GetImage(server .. image)
  obj.Renderer.Material.SetTexture("_MainTex", resrc)
end

function onSmack()

  update()
end

```

### SendNetworkMessageToUser

void SendNetworkMessageToUser(string key, Table message, uint userID)

Sends a networked message to a specific user (userID) with a subscriber listening on 'key'.

المعاملات

| المعامل | النوع  | الوصف                                   |
| ------- | ------ | --------------------------------------- |
| key     | string | Subscription key                        |
| message | Table  | Table/dictionary of serializable values |
| userID  | uint   | Target user ID                          |

القيم المرجعة

`void`

مثال

**Lua**

```lua
Space.Network.SendNetworkMessageToUser('AKey', {first = "xyz", second= "abc"}, 23123123)

```

### SubscribeToRegionPropertyUpdate

void SubscribeToRegionPropertyUpdate(string key, DynValue onRecieve)

Subscribes to region property updates on 'key'.

المعاملات

| المعامل   | النوع            | الوصف                                                                                                |
| --------- | ---------------- | ---------------------------------------------------------------------------------------------------- |
| key       | string           | Property key to subscribe to                                                                         |
| onRecieve | Callback Closure | onRecieve(NetworkPropertyUpdate) will be called on updates. NetworkPropertyUpdate = { Key, Message } |

القيم المرجعة

`void`

مثال

**Lua**

```lua
function onRecieve(NetworkPropertyUpdate)
propertyKey = NetworkPropertyUpdate.Key
propertyValue = NetworkPropertyUpdate.Message
end
Space.Network.SubscribeToRegionPropertyUpdate('A Key', onRecieve)

```

### SubscribeToNetwork

void SubscribeToNetwork(string key, Action< [SNetworkMessageLua ](#)> onRecieve)

void SubscribeToNetwork(string key, DynValue onRecieve)

Subscribes to network messages on 'key', will fire a SNetworkMessage whenever a matching message is received

المعاملات

| المعامل   | النوع            | الوصف                                                                              |
| --------- | ---------------- | ---------------------------------------------------------------------------------- |
| key       | string           | Subscription key to listen on                                                      |
| onRecieve | Callback Closure | Callback receiving SNetworkMessageLua with fields Key (string) and Message (Table) |

القيم المرجعة

`void`

مثال

**Lua**

```lua
function OnRecieveFunction(SNetworkMessageLua)
--
end
Space.Network.SubscribeToNetwork("AKey", OnRecieveFunction)

```

**Lua**

```lua
local scriptedObject = Space.Host.ExecutingObject;
local textValue = Space.Host.GetReference("Text");
scriptedObject.SubscribeToEvents();

-- This function gets used by other objects that are subscribed to the network
gotAMessage = function(arguments)
  textValue.UIText.Text = "Got a message with the argument " .. arguments.Message["someArgument"];
end

-- This function gets used by "this" object. Plus, it sends out a message to objects on the network.
local updateTextUI = function()
  textValue.UIText.Text = "Got a message with the argument Hi there!";
  Space.Network.SendNetworkMessage("helloworld", {someArgument = "Hi there!"});
end

-- Subscribe to network. Note that "this" object doesn't execute gotAMessage.
-- Only the other objects on the network do.
Space.Network.SubscribeToNetwork("helloworld", gotAMessage);

scriptedObject.OnMouseDown(updateTextUI);

-- "Text" used with GetReference is a UItext canvas object used to display the test text inworld. After you add UI > Text to your scene, drag the text object to the Object References section in your script.

```

### SetRegionProperty

void SetRegionProperty(string key, string value)

Stores a key/value pair in the Regions semi-permanent memory. Will be erased when all players exit the region, but will persist as long as the region is open. Subject to rate limiting (10/second on the main grid and 20/second on white-label grids)

المعاملات

| الاسم | النوع  | القيمة الافتراضية |
| ----- | ------ | ----------------- |
| key   | string | –                 |
| value | string | –                 |

القيم المرجعة

`void`

مثال

**Lua**

```lua
Space.Network.SetRegionProperty("testKey", "Test Value") 

```

**Lua**

```lua
 --this script is a networked and persistent color changing of an object
--note that we put the object's GlobalID in the key to make it specific to this object

thisObject = Space.Host.ExecutingObject
currentColor = nil

OnClick = function() --this writes to the region properties
if currentColor == Color.Blue then
  Space.Network.SetRegionProperty(thisObject.GlobalID .. "color", "red")
else
  Space.Network.SetRegionProperty(thisObject.GlobalID .. "color", "blue")
end
  
end

Sync = function() -- this gets from the region properties
  while true do
    local result = Space.Network.GetRegionProperty(thisObject.GlobalID .. "color")
    if result == "red" then
      currentColor = Color.Red 
    else 
      currentColor = Color.Blue
    end

    thisObject.Renderer.Material.SetColor("_Color", currentColor)  
    coroutine.yield(0.1) --to make sure it doesn't run more than 12/second
  end
end


thisObject.AddClickable()
thisObject.Clickable.OnClick(OnClick)
Space.Host.StartCoroutine(Sync)

```

### GetRegionProperty

string GetRegionProperty(string key)

Retrieves the last set value for 'key' in this region. If you have just joined the region, this may not be populated immedietely.

المعاملات

| الاسم | النوع  | القيمة الافتراضية |
| ----- | ------ | ----------------- |
| key   | string | –                 |

القيم المرجعة

`string`

مثال

**Lua**

```lua
 result = Space.Network.GetRegionProperty("testKey")

```

**Lua**

```lua
--this script is a networked and persistent color changing of an object
--note that we put the object's GlobalID in the key to make it specific to this object

thisObject = Space.Host.ExecutingObject
currentColor = nil

OnClick = function() --this writes to the region properties
if currentColor == Color.Blue then
  Space.Network.SetRegionProperty(thisObject.GlobalID .. "color", "red")
else
  Space.Network.SetRegionProperty(thisObject.GlobalID .. "color", "blue")
end
  
end

Sync = function() -- this gets from the region properties
  while true do
    local result = Space.Network.GetRegionProperty(thisObject.GlobalID .. "color")
    if result == "red" then
      currentColor = Color.Red 
    else 
      currentColor = Color.Blue
    end

    thisObject.Renderer.Material.SetColor("_Color", currentColor)  
    coroutine.yield(0.1) --to make sure it doesn't run more than 12/second
  end
end


thisObject.AddClickable()
thisObject.Clickable.OnClick(OnClick)
Space.Host.StartCoroutine(Sync)

```

### SetShardProperty

void SetShardProperty(string key, string value)

Sets a property named 'key' of the Shard to 'value'. Will persist until the Shard is shut down or restarted. (Use SPersistence for longer term storage)

المعاملات

| الاسم | النوع  | القيمة الافتراضية |
| ----- | ------ | ----------------- |
| key   | string | –                 |
| value | string | –                 |

القيم المرجعة

`void`

مثال

**Lua**

```lua
local scriptedObject = Space.Host.ExecutingObject;
scriptedObject.SubscribeToEvents();

local testMsg = "Hello";
local updateTextUI = function()
  Space.Network.SetShardProperty("testKey", testMsg);
end

scriptedObject.OnMouseDown(updateTextUI);

```

### GetShardProperty

string GetShardProperty(string key)

Gets a previously set key.

المعاملات

| الاسم | النوع  | القيمة الافتراضية |
| ----- | ------ | ----------------- |
| key   | string | –                 |

القيم المرجعة

`string`

مثال

**Lua**

```lua
local scriptedObject = Space.Host.ExecutingObject;
scriptedObject.SubscribeToEvents();

local textValue = Space.Host.GetReference("Text");
local retrieved;

local updateTextUI = function()
  retrieved = Space.Network.GetShardProperty("testKey");
end

-- this method is called every frame, once "retrieved" gets a value, it displays in text
local onUpdateMethod = function()
  updateTextUI();
  if retrieved ~= nil then
    textValue.UIText.Text = "Retrieved msg: " .. retrieved ;
  end
end

scriptedObject.OnUpdate(onUpdateMethod);

```

## الخصائص

### HasShardProperties

bool HasShardProperties {get; }

Returns True upon successful connection to the Region/Shard properties' storage. Region/Shard property operations may not be ready when used during initialization and this function ill help determine readiness.

مثال

**Lua**

```lua
IsReady = Space.Network.HasShardProperties

```

**Lua**

```lua
--This script starts but launches a coroutine that waits for HasShardProperties before continuing

DoWhatYouNeed = function(result)
     if property == nil or property == "" then 
Space.Log("connected but Shard doesn't exist")
      else
Space.Log("connected and Shard exists. Result: " .. tostring(result))
      end 
  
  
end


InitCoroutine = function()
    while not Space.Network.HasShardProperties do 
      coroutine.yield(0) 
    end
    
    local property = Space.Network.GetRegionProperty("A Key")
     DoWhatYouNeed(property)
     
end


Space.Host.StartCoroutine(InitCoroutine)

```
