using System; using System.Net.WebSockets; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using BubbleSocketCore.Simulation; namespace BubbleSocketCore.Websocket { public class Connection { private WebSocket websocket; public WebSocketState State { get { return websocket.State; } } public Connection(WebSocket websocket) { this.websocket = websocket; } public WebSocket GetSocket() { return websocket; } public Task SendAsync(SimulationActionType type, object payload, CancellationToken cancellationToken) { var options = new JsonSerializerOptions(); var json = JsonSerializer.Serialize(payload, options); var sendBuffer = Encoding.UTF8.GetBytes($"{SimulationActionFactory.SerializeActionType(type)}{json}"); return websocket.SendAsync(new ArraySegment(sendBuffer, 0, sendBuffer.Length), WebSocketMessageType.Binary, true, cancellationToken); } } }