RPCServerSocketTransport.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Net.Security;
  2. using System.Security.Authentication;
  3. using System.Security.Cryptography.X509Certificates;
  4. using InABox.Core;
  5. using WebSocketSharp;
  6. using WebSocketSharp.Server;
  7. using Logger = InABox.Core.Logger;
  8. namespace InABox.Rpc
  9. {
  10. public class RpcServerSocketTransport : RpcServerTransport<RpcServerSocketConnection>
  11. {
  12. private WebSocketServer? _server;
  13. public static X509Certificate2? Certificate { get; set; }
  14. //public static void InitCertificate(string certificateFile) => Certificate = new X509Certificate2(certificateFile);
  15. public override bool IsSecure() => Certificate != null;
  16. public RpcServerSocketTransport(int port, X509Certificate2? certificate = null)
  17. {
  18. Certificate = certificate;
  19. _server = new WebSocketServer(port, Certificate != null);
  20. if (Certificate != null)
  21. {
  22. _server.SslConfiguration.ServerCertificate = Certificate;
  23. _server.SslConfiguration.ClientCertificateRequired = false;
  24. _server.SslConfiguration.CheckCertificateRevocation = false;
  25. _server.SslConfiguration.ClientCertificateValidationCallback = WSSCallback;
  26. _server.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls12;
  27. }
  28. _server?.AddWebSocketService<RpcServerSocketConnection>("/", (connection) =>
  29. {
  30. connection.Transport = this;
  31. //new RpcServerSocketConnection() { Transport = this };
  32. });
  33. }
  34. private bool WSSCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslpolicyerrors)
  35. {
  36. return true;
  37. }
  38. public override void Start()
  39. {
  40. _server?.Start();
  41. }
  42. public override void Send(RpcServerSocketConnection connection, RpcMessage message)
  43. {
  44. connection.Send(message);
  45. }
  46. public override void Stop()
  47. {
  48. _server?.Stop();
  49. }
  50. public void ConnectionOpened(RpcServerSocketConnection connection)
  51. => DoOpen(connection);
  52. public void ConnectionException(RpcServerSocketConnection connection, Exception e)
  53. => DoException(connection, e);
  54. public void ConnectionClosed(RpcServerSocketConnection connection, CloseEventArgs e)
  55. => DoClose(connection, (e.Code == 1000) ? RpcTransportCloseEventType.Closed : RpcTransportCloseEventType.Error);
  56. }
  57. }