Skip to content

Usage

This guide will walk you through a basic example of setting up a connection, sending, and receiving data.

Setting Up a Transport

Before you can send or receive data, you need to set up a transport. Cobra Transports supports multiple protocols, such as Lidgren (for reliable UDP), TCP, and Websockets. Here's how to set up a basic TCP transport:

using ByteCobra.Transports;
using ByteCobra.Transports.Tcp;

// Initialize your transport
Transport tcpTransport = new TcpTransport();

Starting the Transport

To start listening for incoming connections or connect to a server, use the StartAsync method. Specify the host and port for the connection:

await tcpTransport.StartAsync("localhost", 5000);

Sending Data

To send data, use the SendData or SendDataAsync method. You'll need to serialize your data into a byte array:

string message = "Hello World!";
ByteWriter writer = new ByteWriter();
writer.WriteString(message);
byte[] data = writer.ToArray();
await tcpTransport.SendDataAsync(data);

Sending Data in Unity

When working within Unity, you can't access some objects from a non-main thread because the Unity API is not thread-safe. This is why the Dispatcher class was created. It provides a simple solution to queue actions to be executed on the main thread, where it's safe to interact with Unity objects.

The following example demonstrates how to use the Dispatcher class to safely send data from the main thread:

Dispatcher.Dispatch(() => 
{
    string message = $"Hello from {gameObject.name}";
    ByteWriter writer = new ByteWriter();
    writer.WriteString(message);
    byte[] data = writer.ToArray();
    await tcpTransport.SendDataAsync(data);
});

Receiving Data

To handle incoming data, subscribe to the transport's data events. Use the Subscribe method to add a callback that processes received data:

tcpTransport.Subscribe((data, connection) =>
{
    string message = System.Text.Encoding.UTF8.GetString(data);
    Console.WriteLine($"Received message: {message}");
});

Receiving Data in Unity

To receive data in Unity on the main thread, you must utilize the Dispatcher class, ensuring thread-safe operations.

Handling Connections and Disconnections

To react to connections and disconnections, observe the Connected property on your transport instance. This allows you to execute code based on the connection state:

tcpTransport.Connected.Subscribe( () =>
{
    if (tcpTransport.Connected.Value)
        Console.WriteLine("Connected to the server.");

    else
        Console.WriteLine("Disconnected from the server.");
});

Clean Up

When your application is closing or you no longer need the transport, call Stop to gracefully shut down the transport and release resources:

tcpTransport.Stop();