WebSocket.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. void WebSocket::send(ByteBuffer binary_or_text_message, bool is_text)
  19. {
  20. m_client->send({}, *this, move(binary_or_text_message), is_text);
  21. }
  22. void WebSocket::send(StringView text_message)
  23. {
  24. auto data_result = ByteBuffer::copy(text_message.bytes());
  25. VERIFY(data_result.has_value());
  26. send(data_result.release_value(), true);
  27. }
  28. void WebSocket::close(u16 code, String reason)
  29. {
  30. m_client->close({}, *this, code, move(reason));
  31. }
  32. void WebSocket::did_open(Badge<WebSocketClient>)
  33. {
  34. if (on_open)
  35. on_open();
  36. }
  37. void WebSocket::did_receive(Badge<WebSocketClient>, ByteBuffer data, bool is_text)
  38. {
  39. if (on_message)
  40. on_message(WebSocket::Message { move(data), is_text });
  41. }
  42. void WebSocket::did_error(Badge<WebSocketClient>, i32 error_code)
  43. {
  44. if (on_error)
  45. on_error((WebSocket::Error)error_code);
  46. }
  47. void WebSocket::did_close(Badge<WebSocketClient>, u16 code, String reason, bool was_clean)
  48. {
  49. if (on_close)
  50. on_close(code, move(reason), was_clean);
  51. }
  52. void WebSocket::did_request_certificates(Badge<WebSocketClient>)
  53. {
  54. if (on_certificate_requested) {
  55. auto result = on_certificate_requested();
  56. if (!m_client->set_certificate({}, *this, result.certificate, result.key))
  57. dbgln("WebSocket: set_certificate failed");
  58. }
  59. }
  60. }