menu_bookDocumentation

WebSockets: External Server Communication with Auth Token Support

calendar_today May 20, 2026 schedule ~1 min read person PatrickJr verified 50

s&box allows WebSocket connections to interface with external servers. Common uses include custom networking and persistent data storage outside the local filesystem.

Connection and Messaging

Add a Component to handle WebSocket lifecycle:

CSHARP
public sealed class Server : Component
{
    [Property] public string ConnectionUri { get; set; }
    public WebSocket Socket { get; set; }

    protected override void OnStart()
    {
        Socket = new WebSocket();
        Socket.OnMessageReceived += HandleMessageReceived;
        _ = Connect();
    }

    private async Task Connect()
    {
        await Socket.Connect( ConnectionUri );
        await SendMessage( "Hello!" );
    }

    private async Task SendMessage( string message )
    {
        await Socket.Send( message );
    }

    private void HandleMessageReceived( string message )
    {
        Log.Info( message );
    }
}

Using Auth Tokens with WebSockets

Attach an Auth Token to the WebSocket request header for user validation:

CSHARP
var token = await Sandbox.Services.Auth.GetToken( "YourServiceName" );

if ( string.IsNullOrEmpty( token ) )
    return;

var headers = new Dictionary<string, string>()
{
    { "Authorization", token }
};

await socket.Connect( "ws://localhost:8080", headers );

This validates the connecting user is a legitimate Steam user in a s&box session.

Was this helpful?