summaryrefslogtreecommitdiffstats
blob: 5b4fe22a2f7f2ca1242ec393a2d04e591a858db9 (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
#include "Swiften/Network/Connector.h"

#include <boost/bind.hpp>

#include "Swiften/Network/ConnectionFactory.h"
#include "Swiften/Network/DomainNameResolver.h"
#include "Swiften/Network/DomainNameResolveException.h"

namespace Swift {

Connector::Connector(const String& hostname, DomainNameResolver* resolver, ConnectionFactory* connectionFactory) : hostname(hostname), resolver(resolver), connectionFactory(connectionFactory) {
}

void Connector::start() {
	assert(!currentConnection);
	try {
		std::vector<HostAddressPort> resolveResult = resolver->resolve(hostname.getUTF8String());
		resolvedHosts = std::deque<HostAddressPort>(resolveResult.begin(), resolveResult.end());
		tryNextHostname();
	}
	catch (const DomainNameResolveException&) {
		onConnectFinished(boost::shared_ptr<Connection>());
	}
}

void Connector::tryNextHostname() {
	if (resolvedHosts.empty()) {
		onConnectFinished(boost::shared_ptr<Connection>());
	}
	else {
		HostAddressPort remote = resolvedHosts.front();
		resolvedHosts.pop_front();
		currentConnection = connectionFactory->createConnection();
		currentConnection->onConnectFinished.connect(boost::bind(&Connector::handleConnectionConnectFinished, this, _1));
		currentConnection->connect(remote);
	}
}

void Connector::handleConnectionConnectFinished(bool error) {
	if (error) {
		tryNextHostname();
	}
	else {
		onConnectFinished(currentConnection);
	}
}

};