WebSocket.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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/ByteString.h>
  10. #include <AK/Function.h>
  11. #include <AK/RefCounted.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. ByteString certificate;
  21. ByteString 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. ByteString subprotocol_in_use();
  45. void send(ByteBuffer binary_or_text_message, bool is_text);
  46. void send(StringView text_message);
  47. void close(u16 code = 1005, ByteString reason = {});
  48. Function<void()> on_open;
  49. Function<void(Message)> on_message;
  50. Function<void(Error)> on_error;
  51. Function<void(u16 code, ByteString reason, bool was_clean)> on_close;
  52. Function<CertificateAndKey()> on_certificate_requested;
  53. void did_open(Badge<WebSocketClient>);
  54. void did_receive(Badge<WebSocketClient>, ByteBuffer, bool);
  55. void did_error(Badge<WebSocketClient>, i32);
  56. void did_close(Badge<WebSocketClient>, u16, ByteString, bool);
  57. void did_request_certificates(Badge<WebSocketClient>);
  58. private:
  59. explicit WebSocket(WebSocketClient&, i32 connection_id);
  60. WeakPtr<WebSocketClient> m_client;
  61. int m_connection_id { -1 };
  62. };
  63. }