delete inactive connections

git-svn-id: svn://elaine/murooma/trunk@183 d8a302eb-03bc-478d-80e4-98257eca68ef
This commit is contained in:
(no author) 2014-08-12 06:03:46 +00:00
parent 3e6a1e5b07
commit d0352ce463

View file

@ -19,6 +19,7 @@
#include <iomanip> #include <iomanip>
#include <thread> #include <thread>
#include <memory> #include <memory>
#include <set>
#include "common/chunk.h" #include "common/chunk.h"
#include "common/timeUtils.h" #include "common/timeUtils.h"
#include "common/queue.h" #include "common/queue.h"
@ -50,7 +51,7 @@ std::string return_current_time_and_date()
class Session class Session
{ {
public: public:
Session(socket_ptr sock) : socket_(sock) Session(socket_ptr sock) : active_(false), socket_(sock)
{ {
} }
@ -72,21 +73,31 @@ public:
catch (std::exception& e) catch (std::exception& e)
{ {
std::cerr << "Exception in thread: " << e.what() << "\n"; std::cerr << "Exception in thread: " << e.what() << "\n";
active_ = false;
} }
} }
void start() void start()
{ {
active_ = true;
senderThread = new thread(&Session::sender, this); senderThread = new thread(&Session::sender, this);
// readerThread.join(); // readerThread.join();
} }
void send(shared_ptr<WireChunk> chunk) void send(shared_ptr<WireChunk> chunk)
{ {
while (chunks.size() * WIRE_CHUNK_MS > 10000)
chunks.pop();
chunks.push(chunk); chunks.push(chunk);
} }
bool isActive() const
{
return active_;
}
private: private:
bool active_;
socket_ptr socket_; socket_ptr socket_;
thread* senderThread; thread* senderThread;
Queue<shared_ptr<WireChunk>> chunks; Queue<shared_ptr<WireChunk>> chunks;
@ -110,17 +121,22 @@ public:
cout << "New connection: " << sock->remote_endpoint().address().to_string() << "\n"; cout << "New connection: " << sock->remote_endpoint().address().to_string() << "\n";
Session* session = new Session(sock); Session* session = new Session(sock);
session->start(); session->start();
sessions.push_back(session); sessions.insert(shared_ptr<Session>(session));
} }
} }
void send(shared_ptr<WireChunk> chunk) void send(shared_ptr<WireChunk> chunk)
{ {
for (size_t n=0; n<sessions.size(); ++n) for (std::set<shared_ptr<Session>>::iterator it = sessions.begin(); it != sessions.end(); )
{ {
if (sessions[n] != 0) if (!(*it)->isActive())
sessions[n]->send(chunk); sessions.erase(it++);
} else
++it;
}
for (auto s : sessions)
s->send(chunk);
} }
void start() void start()
@ -134,7 +150,7 @@ public:
} }
private: private:
vector<Session*> sessions; set<shared_ptr<Session>> sessions;
boost::asio::io_service io_service_; boost::asio::io_service io_service_;
unsigned short port_; unsigned short port_;
thread* acceptThread; thread* acceptThread;