summaryrefslogtreecommitdiffstats
blob: 596761ab220612d66ee549915640f0ede8cd0793 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "Swiften/Network/BoostConnectionServer.h"

#include <boost/bind.hpp>
#include <boost/system/system_error.hpp>

#include "Swiften/EventLoop/MainEventLoop.h"

namespace Swift {

BoostConnectionServer::BoostConnectionServer(int port, boost::asio::io_service* ioService) : port_(port), ioService_(ioService), acceptor_(NULL) {
}


void BoostConnectionServer::start() {
	try {
		assert(!acceptor_);
		acceptor_ = new boost::asio::ip::tcp::acceptor(
				*ioService_, 
				boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port_));
		acceptNextConnection();
	}
	catch (const boost::system::system_error& e) {
		if (e.code() == boost::asio::error::address_in_use) {
			onStopped(Conflict);
		}
		else {
			onStopped(UnknownError);
		}
	}
}


void BoostConnectionServer::stop() {
	stop(boost::optional<Error>());
}

void BoostConnectionServer::stop(boost::optional<Error> e) {
	if (acceptor_) {
		acceptor_->close();
		acceptor_ = NULL;
	}
	onStopped(e);
}

void BoostConnectionServer::acceptNextConnection() {
	boost::shared_ptr<BoostConnection> newConnection(new BoostConnection(&acceptor_->io_service()));
	acceptor_->async_accept(newConnection->getSocket(), 
		boost::bind(&BoostConnectionServer::handleAccept, shared_from_this(), newConnection, boost::asio::placeholders::error));
}

void BoostConnectionServer::handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error) {
	if (error) {
		MainEventLoop::postEvent(
				boost::bind(
						&BoostConnectionServer::stop, shared_from_this(), UnknownError), 
				shared_from_this());
	}
	else {
		MainEventLoop::postEvent(
				boost::bind(boost::ref(onNewConnection), newConnection), 
				shared_from_this());
		newConnection->listen();
		acceptNextConnection();
	}
}

}