menu_bookDocumentation

WebSockets - s&box Networking Documentation

calendar_today May 5, 2026 schedule ~1 min read person patrickjr verified 50

WebSockets

s&box supports WebSocket connections for real-time communication with external servers. Use for custom networking, persistent data, or integrating with web services.

Connection and Messaging

Create and connect a WebSocket:

CSHARP
public class MyWebSocket : Component
{
    WebSocket Socket;
    
    protected override async void OnEnabled()
    {
        Socket = new WebSocket();
        await Socket.Connect( "wss://echo.websocket.org" );
        
        // Start receiving
        _ = ReceiveLoop();
    }
    
    async Task ReceiveLoop()
    {
        while ( Socket.IsConnected )
        {
            string message = await Socket.ReceiveAsync();
            Log.Info( $"Received: {message}" );
        }
    }
    
    public async void SendMessage( string message )
    {
        if ( Socket?.IsConnected == true )
        {
            await Socket.SendAsync( message );
        }
    }
    
    protected override void OnDisabled()
    {
        Socket?.Close();
        Socket = null;
    }
}

Using Auth Tokens

Authenticate WebSocket connections:

CSHARP
// Get auth token
var token = await Sandbox.Services.Auth.GetToken();

// Add to headers
var socket = new WebSocket();
socket.Headers.Add( "Authorization", $"Bearer {token}" );
await socket.Connect( "wss://mygame.example.com/ws" );

// Server validates token via Facepunch auth service

Best Practices

  • Handle disconnections gracefully
  • Use async/await to avoid blocking
  • Implement reconnection logic
  • Close sockets when components destroy
  • Validate all incoming messages

Security

  • Use wss:// (secure) for production
  • Auth tokens expire - refresh periodically
  • Only connect to trusted servers
  • Validate message format server-side
Was this helpful?