WebSocket.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibProtocol/WebSocket.h>
  7. #include <LibProtocol/WebSocketClient.h>
  8. namespace Protocol {
  9. WebSocket::WebSocket(WebSocketClient& client, i32 connection_id)
  10. : m_client(client)
  11. , m_connection_id(connection_id)
  12. {
  13. }
  14. WebSocket::ReadyState WebSocket::ready_state()
  15. {
  16. return (WebSocket::ReadyState)m_client->ready_state({}, *this);
  17. }
  18. ByteString WebSocket::subprotocol_in_use()
  19. {
  20. return m_client->subprotocol_in_use({}, *this);
  21. }
  22. void WebSocket::send(ByteBuffer binary_or_text_message, bool is_text)
  23. {
  24. m_client->send({}, *this, move(binary_or_text_message), is_text);
  25. }
  26. void WebSocket::send(StringView text_message)
  27. {
  28. send(ByteBuffer::copy(text_message.bytes()).release_value_but_fixme_should_propagate_errors(), true);
  29. }
  30. void WebSocket::close(u16 code, ByteString reason)
  31. {
  32. m_client->close({}, *this, code, move(reason));
  33. }
  34. void WebSocket::did_open(Badge<WebSocketClient>)
  35. {
  36. if (on_open)
  37. on_open();
  38. }
  39. void WebSocket::did_receive(Badge<WebSocketClient>, ByteBuffer data, bool is_text)
  40. {
  41. if (on_message)
  42. on_message(WebSocket::Message { move(data), is_text });
  43. }
  44. void WebSocket::did_error(Badge<WebSocketClient>, i32 error_code)
  45. {
  46. if (on_error)
  47. on_error((WebSocket::Error)error_code);
  48. }
  49. void WebSocket::did_close(Badge<WebSocketClient>, u16 code, ByteString reason, bool was_clean)
  50. {
  51. if (on_close)
  52. on_close(code, move(reason), was_clean);
  53. }
  54. void WebSocket::did_request_certificates(Badge<WebSocketClient>)
  55. {
  56. if (on_certificate_requested) {
  57. auto result = on_certificate_requested();
  58. if (!m_client->set_certificate({}, *this, result.certificate, result.key))
  59. dbgln("WebSocket: set_certificate failed");
  60. }
  61. }
  62. }