www.pudn.com > FTPServerClient.zip > tcpfactory.cpp


#include  
#include  
#include "tcpfactory.h" 
 
using namespace std; 
 
TcpFactory::TcpFactory() { 
	listenSock = -1; 
} 
 
TcpFactory::~TcpFactory() { 
	if(listenSock!=-1) 
		if(close(listenSock)) throw "Close socket failed"; 
} 
 
void TcpFactory::setDest(int addr, int port) { 
	destAddr = htonl(addr); 
	destPort = htons(port); 
} 
 
void TcpFactory::setDest(const string& addr, int port) { 
	hostent* hp = gethostbyname(addr.c_str()); 
	if(!hp) throw "Resolve address failed"; 
 
	destAddr = *(uint32_t*)hp->h_addr_list[0]; 
	destPort = htons(port); 
} 
 
Tcp* TcpFactory::connect() { 
	int sockfd = socket(AF_INET, SOCK_STREAM, 0); 
	if(sockfd==-1) throw "Create socket failed"; 
 
	sockaddr_in addr; 
	addr.sin_family = AF_INET; 
	addr.sin_addr.s_addr = destAddr; 
	addr.sin_port = destPort; 
 
	if(::connect(sockfd, (sockaddr*)&addr, sizeof addr)) 
		throw "Establish connection failed"; 
 
	cout << "\t[M] Connected to " << inet_ntoa(addr.sin_addr) << ":" << ntohs(destPort) << endl; 
	return new Tcp(sockfd); 
} 
 
void TcpFactory::setLocalPort(int port) { 
	int newPort = htons(port); 
 
	if(localPort!=newPort) { 
		localPort = newPort; 
 
		if(listenSock!=-1) { 
			if(close(listenSock)) throw "Close socket failed"; 
			listenSock = -1; 
		} 
	} 
} 
 
Tcp* TcpFactory::listen() { 
	cout << "\t[M] Listening on local port " << ntohs(localPort) << endl; 
 
	if(listenSock==-1) { 
		listenSock = socket(AF_INET, SOCK_STREAM, 0); 
		if(listenSock==-1) throw "Create socket failed"; 
 
		sockaddr_in addr; 
		addr.sin_family = AF_INET; 
		addr.sin_addr.s_addr = INADDR_ANY; 
		addr.sin_port = localPort; 
 
		if(bind(listenSock, (sockaddr*)&addr, sizeof addr)) 
			throw "Bind listen port failed"; 
 
		if(::listen(listenSock, MAX_CONNECTION)) 
			throw "Listen connection failed"; 
	} 
 
	sockaddr_in addr; 
	socklen_t len = sizeof addr; 
	int sockfd = accept(listenSock, (sockaddr*)&addr, &len); 
	if(sockfd==-1) throw "Accept connection failed"; 
 
	cout << "\t[M] Accept connection from " << inet_ntoa(addr.sin_addr) << ":" << ntohs(addr.sin_port) << endl; 
 
	return new Tcp(sockfd); 
}