CSocket.h 1.5 KB

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