TCPSocketPtr SocketUtil::CreateTCPSocket( SocketAddressFamily inFamily )
{
	SOCKET s = socket( inFamily, SOCK_STREAM, IPPROTO_TCP );
	
	if( s != INVALID_SOCKET )
	{
		return TCPSocketPtr( new TCPSocket( s ) );
	}
	else
	{
		ReportError( "SocketUtil::CreateTCPSocket" );
		return nullptr;
	}
}
void HttpConnectionManager::requestConnection (const Url & url, int timeOutMs, const RequestConnectionCallback & callback) {
	assert (callback);
	{
		// Check the pool
		PendingConnectionMap::iterator i = mPendingConnections.find(ConId(url.protocol(), url.host()));
		if (i != mPendingConnections.end()){
			while (!i->second.empty()){
				AsyncOpId id = i->second.front();
				i->second.pop_front();
				PendingConnectionOp * op;
				getReadyAsyncOp (id, PendingConnection, &op);
				mPendingConnectionsCount--;
				if (op) {
					Log (LogInfo) << LOGID << "Reusing connection to " << url.protocol() << "/" << url.host() << " id=" << op->id() << std::endl;
					xcall (abind(callback, NoError, op->connection));
					delete op;
					return;
				}
			}
			// not existant anymore
			mPendingConnections.erase (i);
		}
	}
	EstablishConnectionOp * op = new EstablishConnectionOp (regTimeOutMs (timeOutMs));

	const String & protocol = url.protocol();
	if (protocol != "http" && protocol != "https") {
		Log (LogWarning) << LOGID << "Unsupported protocol: " << protocol << std::endl;
		return xcall(abind(callback, error::NotSupported, HttpConnectionPtr()));
	}
	op->callback = callback;
	op->connection = HttpConnectionPtr (new HttpConnection());
	op->connection->host = url.host();
	op->connection->pureHost = url.pureHost();
	op->connection->protocol = url.protocol();
	TCPSocketPtr sock = TCPSocketPtr (new TCPSocket ());
	op->connection->channel = sock;
	op->setId(genFreeId());
	op->setState(EstablishConnectionOp::WaitTcpConnect);
	Error e = sock->connectToHost(url.pureHost(), url.port(), timeOutMs, abind(dMemFun(this, &HttpConnectionManager::onTcpConnect), op->id()));
	if (e) {
		delete op;
		return xcall (abind(callback, e, HttpConnectionPtr()));
	}
	addAsyncOp (op);
}