Socket.h 1.8 KB

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