CSocket.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #pragma once
  2. #include <LibCore/CIODevice.h>
  3. #include <LibCore/CSocketAddress.h>
  4. class CNotifier;
  5. class CSocket : public CIODevice {
  6. C_OBJECT(CSocket)
  7. public:
  8. enum class Type {
  9. Invalid,
  10. TCP,
  11. UDP,
  12. Local,
  13. };
  14. virtual ~CSocket() override;
  15. Type type() const { return m_type; }
  16. bool connect(const String& hostname, int port);
  17. bool connect(const CSocketAddress&, int port);
  18. bool connect(const CSocketAddress&);
  19. ByteBuffer receive(int max_size);
  20. bool send(const ByteBuffer&);
  21. bool is_connected() const { return m_connected; }
  22. void set_blocking(bool blocking);
  23. CSocketAddress source_address() const { return m_source_address; }
  24. int source_port() const { return m_source_port; }
  25. CSocketAddress destination_address() const { return m_source_address; }
  26. int destination_port() const { return m_destination_port; }
  27. Function<void()> on_connected;
  28. Function<void()> on_ready_to_read;
  29. protected:
  30. CSocket(Type, CObject* parent);
  31. CSocketAddress m_source_address;
  32. CSocketAddress m_destination_address;
  33. int m_source_port { -1 };
  34. int m_destination_port { -1 };
  35. bool m_connected { false };
  36. virtual void did_update_fd(int) override;
  37. private:
  38. virtual bool open(CIODevice::OpenMode) override { ASSERT_NOT_REACHED(); }
  39. bool common_connect(const struct sockaddr*, socklen_t);
  40. void ensure_read_notifier();
  41. Type m_type { Type::Invalid };
  42. RefPtr<CNotifier> m_notifier;
  43. RefPtr<CNotifier> m_read_notifier;
  44. };