Example #1
0
int NetWork::connect(const char *ip, unsigned short port, bool encrypt)
{
	int handle = -1;
	TcpConnection *conn = new TcpConnection(this);

//	if(encrypt) conn->set_encrypt();
	if (conn->connect(ip, port)) {
		if (_online_user.addconn(conn)) {
			_sock_event->add_event(conn, true, true);
			handle = conn->gethandle();
		}
	} else {
		LOGI("NetWork::connect connect fail : %s", strerror(errno));
		//如果连接失败,将底层的网络错误码的负值返回回去;
		handle = (conn->last_sys_errno() * (-1));
		delete conn;
	}

	return handle;
}
Example #2
0
int Network::Server::initConnection(const char* host, const char* port)
{
	if (strlen(host) > INET6_ADDRSTRLEN || strlen(port) > MAX_PORT_LENGTH )
	{
		DEBUGPRINT("SERVER ERROR:\t Invalid port or host length to init\n");
		return -2;
	}
	
	if (host == NULL || port == NULL)
	{
		DEBUGPRINT("SERVER ERROR:\t Invalid arguments to init\n");
	} 
	
	LOGPRINT("SERVER STATUS:\t Connection to host:%s:%s\n", host, port);
	
	addrinfo l_hints, *l_result, *l_p;
	int l_resvalue = -1;
	
	memset(&l_hints, 0, sizeof(struct addrinfo) );
	
	l_hints.ai_family = AF_UNSPEC;
	l_hints.ai_socktype = SOCK_STREAM;
	
	if ((l_resvalue = getaddrinfo(host, port, &l_hints, &l_result)) == -1)
	{
		DEBUGPRINT("SERVER ERROR:\t Could not get addrinfo: %s\n", gai_strerror(l_resvalue));
		return -1;
	}
	
	TcpConnection * conn = new TcpConnection();
	
	if (conn == NULL)
	{
		DEBUGPRINT("SERVER ERROR:\t Could not create new TCP Connection\n");
		return -1;
	}

	for (l_p = l_result; l_p != NULL; l_p = l_p->ai_next)
	{
		if ((l_resvalue =conn->socket(l_p)) != 0)
		{
			if (l_resvalue == -1) 
			{
				DEBUGPRINT("SERVER ERROR:\t Could not connect socket trying next\n");
			} else if (l_resvalue == -2)
			{
				DEBUGPRINT("SERVER ERROR:\t Argument error to socket\n");
			} else 
			{
				DEBUGPRINT("SERVER ERROR:\t Invalid Return\n");
			}
			continue;
		}
		
		if ((l_resvalue = conn->connect(l_p)) != 0)
		{
			if (l_resvalue == -1)
			{
				DEBUGPRINT("SERVER ERROR:\t Could not connect to server/port\n");
			} else if (l_resvalue == -2)
			{
				DEBUGPRINT("SERVER ERROR:\t Argument error to connect\n");
			} else {
				DEBUGPRINT("SERVER ERROR:\t Invalid return\n");
			}
			conn->close();
			continue;
		}
		
		break;
	}
	
	if (l_p == NULL)
	{
		DEBUGPRINT("SERVER FAILURE:\t Failed to connect to %s:%s\n", host, port);
		return -1;
	}
	
	int fileDesc = conn->getSocketFd();
	int enable = 1;
	
	if (setsockopt(fileDesc, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) == -1)
	{
		return -1;	
	}
	
	if ( setnonblock(fileDesc) == -1)
	{
		DEBUGPRINT("SERVER ERROR:\t Could not set socket to non-blocking\n");
	}
	
	if( addHandler(fileDesc, EPOLLET|EPOLLIN|EPOLLHUP, conn ) == -1)
	{
		DEBUGPRINT("SERVER ERROR:\t Could not add handler to tcpConnection\n");
		return -1;
	}
	
	
	
	return fileDesc;

}