diff C++/SocketListener.h @ 245:3c12f0e8bbb9

Converter: add cstring missing Sockets: * Starts a PIMPL idiom to safely cast Socket with the future SocketSsl and be able to return a class of type "Socket" whilst the interface returns effectively a SocketSsl. * Rename some function to be more cute to use like getDomain -> domain(). * SocketListener now owns completely sockets and must be moved to it, the dedicated function select() always return a socket owned by SocketListener. * Operation close is not needed anymore but the function stays in case it's needed.
author David Demelier <markand@malikania.fr>
date Sun, 28 Sep 2014 21:15:26 +0200
parents 9fc5f917872b
children 806dbb6011c7
line wrap: on
line diff
--- a/C++/SocketListener.h	Sat Sep 13 19:42:15 2014 +0200
+++ b/C++/SocketListener.h	Sun Sep 28 21:15:26 2014 +0200
@@ -27,9 +27,9 @@
  * @class SocketTimeout
  * @brief thrown when a timeout occured
  */
-class SocketTimeout : public std::exception {
+class SocketTimeout final : public std::exception {
 public:
-	virtual const char * what(void) const throw();
+	const char *what() const noexcept override;
 };
 
 /**
@@ -38,24 +38,31 @@
  *
  * Convenient wrapper around the select() system call.
  */
-class SocketListener {
+class SocketListener final {
 private:
-	std::vector<Socket> m_clients;
+	std::vector<Socket> m_sockets;
 
 public:
 	/**
+	 * Create a socket listener with a specific number of sockets to reserve.
+	 *
+	 * @param count the number of socket to reserve (default: 0)
+	 */
+	SocketListener(int count = 0);
+
+	/**
 	 * Add a socket to listen to.
 	 *
 	 * @param s the socket
 	 */
-	void add(Socket &s);
+	void add(Socket &&s);
 
 	/**
 	 * Remove a socket from the list.
 	 *
 	 * @param s the socket
 	 */
-	void remove(Socket &s);
+	void remove(const Socket &s);
 
 	/**
 	 * Remove every sockets in the listener.
@@ -73,13 +80,30 @@
 	 * Wait for an event in the socket list. If both s and us are set to 0 then
 	 * it waits indefinitely.
 	 *
+	 * Taking ownership of the returned socket is undefined behaviour.
+	 *
 	 * @param s the timeout in seconds
 	 * @param us the timeout in milliseconds
-	 * @return the socket ready
+	 * @see take
+	 * @return the socket ready owner by the SocketListener
 	 * @throw SocketError on error
 	 * @throw SocketTimeout on timeout
 	 */
 	Socket &select(int s = 0, int us = 0);
+
+	/**
+	 * Take back all sockets that listener own.
+	 *
+	 * @param func the function to call (void f(Socket &&s))
+	 */
+	template <typename Func>
+	void take(Func func)
+	{
+		for (auto &x : m_sockets)
+			func(std::move(x));
+
+		clear();
+	}	
 };
 
 #endif // !_SOCKET_LISTENER_H_