WebSocket.cpp 1.6 KB

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