Socket.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. virtual bool close() override;
  35. virtual void set_idle(bool);
  36. Function<void()> on_connected;
  37. Function<void()> on_error;
  38. Function<void()> on_ready_to_read;
  39. protected:
  40. Socket(Type, Object* parent);
  41. SocketAddress m_source_address;
  42. SocketAddress m_destination_address;
  43. int m_source_port { -1 };
  44. int m_destination_port { -1 };
  45. bool m_connected { false };
  46. virtual void did_update_fd(int) override;
  47. virtual bool common_connect(const struct sockaddr*, socklen_t);
  48. private:
  49. virtual bool open(OpenMode) override { VERIFY_NOT_REACHED(); }
  50. void ensure_read_notifier();
  51. Type m_type { Type::Invalid };
  52. RefPtr<Notifier> m_notifier;
  53. RefPtr<Notifier> m_read_notifier;
  54. };
  55. }
  56. template<>
  57. struct AK::Formatter<Core::Socket> : Formatter<Core::Object> {
  58. };