Connection.cs 954 B

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using BubbleSocketCore.Simulation;
  8. namespace BubbleSocketCore.Websocket
  9. {
  10. public class Connection
  11. {
  12. private WebSocket websocket;
  13. public WebSocketState State { get { return websocket.State; } }
  14. public Connection(WebSocket websocket)
  15. {
  16. this.websocket = websocket;
  17. }
  18. public WebSocket GetSocket()
  19. {
  20. return websocket;
  21. }
  22. public Task SendAsync(SimulationActionType type, object payload, CancellationToken cancellationToken)
  23. {
  24. var options = new JsonSerializerOptions();
  25. var json = JsonSerializer.Serialize(payload, options);
  26. var sendBuffer = Encoding.UTF8.GetBytes($"{SimulationActionFactory.SerializeActionType(type)}{json}");
  27. return websocket.SendAsync(new ArraySegment<byte>(sendBuffer, 0, sendBuffer.Length), WebSocketMessageType.Binary, true, cancellationToken);
  28. }
  29. }
  30. }