Socket.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Function.h>
  8. #include <AK/Span.h>
  9. #include <LibCore/IODevice.h>
  10. #include <LibCore/SocketAddress.h>
  11. namespace Core {
  12. class Socket : public IODevice {
  13. C_OBJECT(Socket)
  14. public:
  15. enum class Type {
  16. Invalid,
  17. TCP,
  18. UDP,
  19. Local,
  20. };
  21. virtual ~Socket() override;
  22. Type type() const { return m_type; }
  23. virtual bool connect(const String& hostname, int port);
  24. bool connect(const SocketAddress&, int port);
  25. bool connect(const SocketAddress&);
  26. ByteBuffer receive(int max_size);
  27. bool send(ReadonlyBytes);
  28. bool is_connected() const { return m_connected; }
  29. void set_blocking(bool blocking);
  30. SocketAddress source_address() const { return m_source_address; }
  31. int source_port() const { return m_source_port; }
  32. SocketAddress destination_address() const { return m_destination_address; }
  33. int destination_port() const { return m_destination_port; }
  34. Function<void()> on_connected;
  35. Function<void()> on_ready_to_read;
  36. protected:
  37. Socket(Type, Object* parent);
  38. SocketAddress m_source_address;
  39. SocketAddress m_destination_address;
  40. int m_source_port { -1 };
  41. int m_destination_port { -1 };
  42. bool m_connected { false };
  43. virtual void did_update_fd(int) override;
  44. virtual bool common_connect(const struct sockaddr*, socklen_t);
  45. private:
  46. virtual bool open(OpenMode) override { VERIFY_NOT_REACHED(); }
  47. void ensure_read_notifier();
  48. Type m_type { Type::Invalid };
  49. RefPtr<Notifier> m_notifier;
  50. RefPtr<Notifier> m_read_notifier;
  51. };
  52. }
  53. template<>
  54. struct AK::Formatter<Core::Socket> : Formatter<Core::Object> {
  55. };