WebSockets
s&box allows you to use WebSockets to interface with an external server. Common usages include custom networking, or persisting data outside of a local filesystem.
Example
Adding this component to a GameObject in the scene will ensure the connection is started when the game starts.
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 bozers" );
}
private async Task SendMessage( string message ) {
await Socket.Send( message );
}
private void HandleMessageReceived( string message )
{
Log.Info( message );
}
}
Using Auth Tokens
You could attach an Auth Token to your WebSocket request header like so:
var token = await Sandbox.Services.GetToken( "YourServiceName" );
if ( string.IsNullOrEmpty( token ) )
{
Log.Info( "Unable to fetch a valid session token..." );
return;
}
var headers = new Dictionary<string, string>()
{
{ "Authorization", token }
};
await socket.Connect( "ws://localhost:8080", headers );