S&box Wiki

Revision Difference

websockets#560530

<cat>Code.Network</cat> <title>Websockets</title> ⤶ <note>Page needs to be entirely rewritten for the scene system, lets wait until networking is more finalized though.</note>⤶ # WebSockets⤶ ⤶ s&box allows you to use [WebSockets](https://en.wikipedia.org/wiki/WebSocket) 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.⤶ ⤶ ```csharp⤶ public sealed class Server : Component⤶ {⤶ // Example: wss://host.example:443/ws⤶ [Property] public string ConnectionUri { get; set; }⤶ public WebSocket Socket { get; set; }⤶ ⤶ protected override void OnStart()⤶ {⤶ Socket = new WebSocket();⤶ Socket.OnMessageReceived += HandleMessageReceived;⤶ _ = Connect();⤶ }⤶ ⤶ // Connect to the server and send a message⤶ private async Task Connect()⤶ {⤶ await Socket.Connect( ConnectionUri );⤶ await SendMessage( "hello bozers" );⤶ }⤶ ⤶ private async Task SendMessage( string message ) {⤶ await Socket.Send( message );⤶ }⤶ ⤶ // Log our received messages⤶ private void HandleMessageReceived( string message )⤶ {⤶ Log.Info( message );⤶ }⤶ }⤶ ```⤶ ⤶ ## Using Auth Tokens⤶ ⤶ You could attach an [Auth Token](AuthTokens) to your WebSocket request header like so:⤶ ⤶ ```csharp⤶ 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 );⤶ ```