00001 /* 00002 * GenericServer.h 00003 * 00004 * Created on: 23.04.2010 00005 * Author: morgenro 00006 */ 00007 00008 #ifndef GENERICSERVER_H_ 00009 #define GENERICSERVER_H_ 00010 00011 #include "Component.h" 00012 #include <ibrcommon/thread/MutexLock.h> 00013 #include <ibrcommon/thread/Thread.h> 00014 #include <ibrcommon/thread/Mutex.h> 00015 #include <ibrcommon/thread/Conditional.h> 00016 #include <ibrcommon/thread/Queue.h> 00017 #include <list> 00018 #include <algorithm> 00019 00020 namespace dtn 00021 { 00022 namespace net 00023 { 00024 class GenericConnectionInterface 00025 { 00026 protected: 00027 virtual ~GenericConnectionInterface() { }; 00028 00029 public: 00030 virtual void initialize() = 0; 00031 virtual void shutdown() = 0; 00032 }; 00033 00034 template <class T> 00035 class GenericServer : public dtn::daemon::IndependentComponent 00036 { 00037 public: 00038 GenericServer() 00039 { } 00040 00041 virtual ~GenericServer() 00042 { } 00043 00044 ibrcommon::Mutex& mutex() 00045 { 00046 return _lock; 00047 } 00048 00049 void add(T *obj) 00050 { 00051 _clients.push_back(obj); 00052 connectionUp(obj); 00053 } 00054 00055 void remove(T *obj) 00056 { 00057 _clients.erase( std::remove( _clients.begin(), _clients.end(), obj), _clients.end() ); 00058 connectionDown(obj); 00059 } 00060 00061 protected: 00062 virtual T* accept() = 0; 00063 virtual void listen() = 0; 00064 virtual void shutdown() = 0; 00065 00066 bool __cancellation() 00067 { 00068 shutdown(); 00069 return true; 00070 } 00071 00072 virtual void connectionUp(T *conn) = 0; 00073 virtual void connectionDown(T *conn) = 0; 00074 00075 void componentUp() 00076 { 00077 listen(); 00078 } 00079 00080 void componentRun() 00081 { 00082 try { 00083 while (true) 00084 { 00085 T* obj = accept(); 00086 00087 { 00088 ibrcommon::MutexLock l(_lock); 00089 add(obj); 00090 } 00091 00092 // initialize the object 00093 obj->initialize(); 00094 00095 // breakpoint 00096 ibrcommon::Thread::yield(); 00097 } 00098 } catch (std::exception) { 00099 // ignore all errors 00100 return; 00101 } 00102 } 00103 00104 void componentDown() 00105 { 00106 while (true) 00107 { 00108 T* client = NULL; 00109 { 00110 ibrcommon::MutexLock l(_lock); 00111 if (_clients.empty()) break; 00112 client = _clients.front(); 00113 _clients.remove(client); 00114 } 00115 00116 client->shutdown(); 00117 } 00118 00119 shutdown(); 00120 } 00121 00122 ibrcommon::Mutex _lock; 00123 std::list< T* > _clients; 00124 }; 00125 00126 template <class T> 00127 class GenericConnection : public GenericConnectionInterface 00128 { 00129 public: 00130 GenericConnection(GenericServer<T> &server) : _server(server) { }; 00131 virtual ~GenericConnection() { }; 00132 00133 protected: 00134 GenericServer<T> &_server; 00135 }; 00136 } 00137 } 00138 00139 #endif /* GENERICSERVER_H_ */
1.7.1