WebSocket.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Badge.h>
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Function.h>
  10. #include <AK/RefCounted.h>
  11. #include <AK/String.h>
  12. #include <AK/WeakPtr.h>
  13. #include <LibCore/Notifier.h>
  14. #include <LibIPC/Forward.h>
  15. namespace Protocol {
  16. class WebSocketClient;
  17. class WebSocket : public RefCounted<WebSocket> {
  18. public:
  19. struct CertificateAndKey {
  20. String certificate;
  21. String key;
  22. };
  23. struct Message {
  24. ByteBuffer data;
  25. bool is_text { false };
  26. };
  27. enum class Error {
  28. CouldNotEstablishConnection,
  29. ConnectionUpgradeFailed,
  30. ServerClosedSocket,
  31. };
  32. enum class ReadyState {
  33. Connecting = 0,
  34. Open = 1,
  35. Closing = 2,
  36. Closed = 3,
  37. };
  38. static NonnullRefPtr<WebSocket> create_from_id(Badge<WebSocketClient>, WebSocketClient& client, i32 connection_id)
  39. {
  40. return adopt_ref(*new WebSocket(client, connection_id));
  41. }
  42. int id() const { return m_connection_id; }
  43. ReadyState ready_state();
  44. void send(ByteBuffer binary_or_text_message, bool is_text);
  45. void send(StringView text_message);
  46. void close(u16 code = 1005, String reason = {});
  47. Function<void()> on_open;
  48. Function<void(Message)> on_message;
  49. Function<void(Error)> on_error;
  50. Function<void(u16 code, String reason, bool was_clean)> on_close;
  51. Function<CertificateAndKey()> on_certificate_requested;
  52. void did_open(Badge<WebSocketClient>);
  53. void did_receive(Badge<WebSocketClient>, ByteBuffer, bool);
  54. void did_error(Badge<WebSocketClient>, i32);
  55. void did_close(Badge<WebSocketClient>, u16, String, bool);
  56. void did_request_certificates(Badge<WebSocketClient>);
  57. private:
  58. explicit WebSocket(WebSocketClient&, i32 connection_id);
  59. WeakPtr<WebSocketClient> m_client;
  60. int m_connection_id { -1 };
  61. };
  62. }