///////////////////////////////////////////////////////////////// // Reciever.cpp - Demonstration of socket reciever with // // concurrent clients // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2013 // ///////////////////////////////////////////////////////////////// /* * This Reciever expects to read lines of text only. * So message framing is done by lines. * * For HTTP like protocols the Reciever should expect * lines in the header and bytes in the body, if there is one, * specified by a header line something like: * content_length : 1024 * where 1024 is a stand-in for whatever you want your block * size to be. * */ /* * Required files: * - Reciever.cpp, Sockets.h, Sockets.cpp, * Threads.h, Threads.cpp, Locks.h, Locks.cpp * BlockingQueue.h, BlockingQueue.cpp * * Maintanence History: * ver 1.1 - 30 Mar 2013 * - changes to error handling * ver 1.0 - 29 Mar 2013 * - first release */ #include "../Sockets/Sockets.h" #include "../Threads/Threads.h" #include "../Threads/Locks.h" #include "../BlockingQueue/BlockingQueue.h" #include /////////////////////////////////////////////////// // ClientHandlerThread thread class ClientHandlerThread : public tthreadBase { public: ClientHandlerThread(Socket s, BlockingQueue& q) : s_(s), q_(q) {} private: void run() { std::string msg; do { doLog("receive thread reading line"); msg = s_.readLine(); if(msg == "") break; q_.enQ(msg); } while(msg != "quit"); } Socket s_; BlockingQueue& q_; }; /////////////////////////////////////////////////// // listenThread thread class ListenThread : public threadBase { public: ListenThread(int port, BlockingQueue& q) : listener_(port), q_(q), stop_(false) {} void stop(bool end) { stop_ = end; } private: void run() { while(!stop_) { SOCKET s = listener_.waitForConnect(); ClientHandlerThread* pCh = new ClientHandlerThread(s, q_); pCh->start(); } } bool stop_; BlockingQueue& q_; SocketListener listener_; }; class Receiver { public: void start(int port) { sout << "Reciever started\n"; pLt = new ListenThread(port, q_); try { pLt->start(); std::string msg; int count = 0; do { msg = q_.deQ(); doLog((std::string("fetching message ") + msg).c_str()); sout << " Recieved from " << msg.c_str(); } while(true); } catch(std::exception& ex) { delete pLt; } catch(...) { delete pLt; } } private: BlockingQueue q_; ListenThread* pLt; }; int main() { int ret = 0; try { Receiver rcvr; rcvr.start(8080); } catch(std::exception& ex) { std::cout << "\n\n " << ex.what(); ret = 1; } catch(...) { sout << "\n something bad happened"; ret = 1; } sout << "\n\n"; return ret; }