RPCServerSocketConnection.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using InABox.Core;
  2. using WebSocketSharp;
  3. using WebSocketSharp.Server;
  4. using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;
  5. namespace InABox.Rpc
  6. {
  7. public class RpcServerSocketConnection: WebSocketBehavior
  8. {
  9. public RpcServerSocketTransport? Transport { get; set; }
  10. protected override void OnOpen()
  11. {
  12. base.OnOpen();
  13. Transport?.ConnectionOpened(this);
  14. }
  15. protected override void OnClose(CloseEventArgs e)
  16. {
  17. base.OnClose(e);
  18. Transport?.ConnectionClosed(this,e);
  19. }
  20. protected override void OnError(ErrorEventArgs e)
  21. {
  22. base.OnError(e);
  23. Transport?.ConnectionException(this, e.Exception);
  24. }
  25. protected override void OnMessage(MessageEventArgs e)
  26. {
  27. base.OnMessage(e);
  28. Task.Run(() =>
  29. {
  30. RpcMessage? request = null;
  31. if (e.IsBinary && (e.RawData != null))
  32. request = Serialization.ReadBinary<RpcMessage>(e.RawData, BinarySerializationSettings.Latest);
  33. else if (e.IsText && !String.IsNullOrWhiteSpace(e.Data))
  34. request = Serialization.Deserialize<RpcMessage>(e.Data);
  35. RpcMessage? response = Transport?.DoMessage(this, request);
  36. if (response != null)
  37. {
  38. if (e.IsBinary)
  39. Send(Serialization.WriteBinary(response, BinarySerializationSettings.Latest));
  40. else
  41. {
  42. Send(Serialization.Serialize(response));
  43. }
  44. }
  45. });
  46. }
  47. public void Send(RpcMessage message)
  48. {
  49. Send(Serialization.WriteBinary(message, BinarySerializationSettings.Latest));
  50. }
  51. }
  52. }