Categories

Creating simple messaging between devices

Now we will write the minimum necessary code to use Bluetooth Mobile Multiplayer, which will send a message from the server to the client, and it will send it back

Сlient side:

public class MyScript : MonoBehaviour
{
public BluetoothClient client;

private void Start()
{
if (client == null)
{
client = BluetoothClient.CreateClient();
}
client.OnFinishedInit += FinishInit;
client.Init();
}

private void FinishInit(BluetoothClient client, int status, string ErrorMessage)
{
client.OnFinishedInit -= FinishInit;
if (status == 0 && string.IsNullOrEmpty(ErrorMessage))
{
Debug.Log("BluetoothClient inited");
SubscribeCallback();
client.StartAdvertising();
}
else
{
Debug.LogError("BluetoothClient failed init. status = " + status + " | Error: " + ErrorMessage);
}
}

private void SubscribeCallback()
{
client.OnAdvertisingStarted += (BluetoothClient client, int status, string ErrorMessage) =>
{
if (status == 0 && string.IsNullOrEmpty(ErrorMessage))
{
Debug.Log("BluetoothClient AdvertisingStarted");
}
else
{
Debug.LogError("BluetoothClient failed AdvertisingStarted. status = " + status + " | Error: " + ErrorMessage);
}
};

client.OnReceivingMessage += (string data) =>
{
Debug.Log("ReceivingMessage:: " + data);
client.SendData(data);
};
}
}

Server side:

public class MyScript : MonoBehaviour
{
public BluetoothServer server;
private bool IsDeviceConnected = false;

private void Start()
{
if (server == null)
{
server = BluetoothServer.CreateServer();
}
server.OnFinishedInit += FinishInit;
server.Init();
}

private void FinishInit(BluetoothServer server, int status, string ErrorMessage)
{
server.OnFinishedInit -= FinishInit;
if (status == 0 && string.IsNullOrEmpty(ErrorMessage))
{
Debug.Log("BluetoothServer inited");
SubscribeCallback();
Debug.Log("BluetoothServer start scan devices");
server.StartScan(7f, FinishScan);
}
else
{
Debug.LogError("BluetoothServer failed init. status = " + status + " | Error: " + ErrorMessage);
}
}

private void SubscribeCallback()
{
server.OnReceivingMessage += (string Message) =>
{
Debug.Log("ReceivingMessage:: " + Message);
};

server.OnConnectsCompleted += (List<BluetoothDevice> devices) =>
{
if (devices.Count > 0)
{
Debug.Log("Successful connection to devices");
IsDeviceConnected = true;
}
};
}

private void FinishScan()
{
Debug.Log("BluetoothServer finished scanning devices. Start connecting devices");
server.ConnectDevices();
}

// Сall this method to send a message
public void SendMsg(string _msg)
{
if (IsDeviceConnected)
{
server.SendData(_msg);
}
else
{
Debug.Log("no device detected, try searching again!");
server.StartScan(7f, FinishScan);
}
}

}