Exemple #1
0
    void DAQPipe::connect()
    {

        printf("Connecting to %s on port %d... ",m_hostid,m_port);

        #ifdef WIN32
        {
            struct sockaddr_in server;
            hostent *hp;
            SOCKET sock;
            int retval;

            if (! (hp = gethostbyname(m_hostid))
                || (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
            {
                std::cerr << "Error resolving XCALDAQ server spec: "<<WSAGetLastError() << std::endl;
                throw std::runtime_error("Failed to resolve XCALDAQ specification");
            }
            memcpy((char *)&server.sin_addr, hp->h_addr_list[0], hp->h_length);
            server.sin_port = htons((short)portnum);
            server.sin_family = AF_INET;

            do
            retval = connect(sock, (struct sockaddr *) &server, sizeof(server));
            while (retval == -1 && errno == EINTR);
            if (retval == -1)
            {
                closesocket(sock);
                throw std::runtime_error("Failed to connect to XCALDAQ server");
            }
            m_socketID = sock;
        }
        #else
        {
            m_socketID = -1;
            // try to get an adress once
            m_socketID = u_connect(m_port,m_hostid);

            if (m_socketID == -1)
            {
                // print an error
                std::cout << std::endl << "Can't connect to host "<< m_hostid << " on port " << m_port;

                // throw std::runtime_error("Failed to connect to XCALDAQ server");
                m_fdValid = false;

                std::cout << "failed!" << std::endl;

            }
            else
            {
                m_fdValid = true;
                std::cout << "done!" << std::endl;
            }

        }
        #endif

    }
/*
This function is used to execute in a thread.
It will connect a server with hostname and port number.
It will send a full path of the named filename under the current working directory
to the server.
The server will return back a point to a number, if successful is 0, failed is 1.
The mutex lock is used to lock the communication process.
*/
void *threadconnect(void *arg) {
    char flag[1];
    int flag_num;
    int bytescopied;
    int communfd;
    int error;
    char compilepath[BLKSIZE];
    int i =0;
    const char *str_name;

    struct connectpara *cp;
    cp = (struct connectpara *)(arg);

    u_port_t pn = 0;
    char *hn = NULL;
    char *fn = NULL;

    pn = (*cp).portnumber;
    hn = (*cp).hostname;
    fn = (*cp).filename;

    if ((communfd = u_connect(pn, hn)) == -1) {
        perror("Failed to establish connection");
        return NULL;
    }
    fprintf(stderr, "[%ld]:connection made to %s\n", (long)getpid(), hn);

    str_name = fn;

    getcwd(compilepath, BLKSIZE);

    strcat(compilepath, "/");
    strcat(compilepath, str_name);
    strcat(compilepath, "\n");

    if(r_write(communfd, compilepath, strlen(compilepath)) < 0) {
        fprintf(stderr, "Could not write to communfd\n");
        return NULL;
    }

    if ((i = r_read(communfd, flag, 1)) < 0) {		//read flag from STDOUT_FILENO
        fprintf(stderr, "Could not read flag from communfd.\n");
        return NULL;
    }

    if(flag_num = (int) atoi(flag)) {
        return &one;
    }
    else {
        return &zero;
    }
}
Exemple #3
0
/* Open a connection to the given host and port for logging.
 * If host is NULL, use the environment variable LOGGINGHOST if it is set;
 *    otherwise, use the host "localhost".
 * If port is 0, use the environment variable LOGGINGPORT if it is set;
 *    otherwise, use the default port DEFAULT_PORT.
 * Return a pointer to an LFILE if successful, or NULL if unsuccessful.
*/
LFILE *lopen(char *host, int port) {
   int fd;
   LFILE *mf;
   char *portstr;

   if (host == NULL) {
      host = getenv("LOGGINGHOST");
      if (host == NULL)
         host = DEFAULT_HOST;
   }
   if (port <= 0) {
      portstr = getenv("LOGGINGPORT");
      if (portstr == NULL)
         port = DEFAULT_PORT;
      else
         port = atoi(portstr);
   }
   fd = u_connect(port, host);
   if (fd < 0) {
      if (ldebug_flag)
         fprintf(stderr, "Connection failed to host %s on port %d\n",
                 host,port);
      return NULL;
   }
   mf = (LFILE *)malloc(sizeof(LFILE));
   if (mf == NULL) {
      if (ldebug_flag)
         fprintf(stderr, "Memory allocation error for lopen\n");
      return NULL;
   }   
#ifdef LUSETHREAD
   if (pthread_mutex_lock(&ID_mutex))
      return NULL;
#endif
   mf->id = nextID++;
#ifdef LUSETHREAD
   if (pthread_mutex_unlock(&ID_mutex))
      return NULL;
#endif
   mf->fd = fd;
   mf->tmode = 0;
   mf->gen[0] = 0;
   go_through_pipe(mf);
#ifdef LSENDTIME
   lsendtime(mf);
#endif
   return mf;
}    
Exemple #4
0
int abreConexao(IdPeer& peer)
{
	char sIp[TAM_STR_IP+1];
	int sockfd;
	
	printf("****Entrei****\n");
	
	IdPeer2StrIp(sIp, peer);
	
	printf("Vou tentar estabelecer nova conexao com o peer: %s\n", sIp);
	sockfd = u_connect(peer.porta, sIp);
	printf("Socket: %d\n", sockfd);
	
	FD_SET(sockfd, &allset); 	// Seta o bit para o novo descritor no set de descritores q estao sendo tratados por "select"
	
	if(sockfd > maxfd)
		maxfd = sockfd;
	
	printf("****Saindo****\n");
		
	return sockfd;
}
Exemple #5
0
void * SelecionaDescritores(void *args) {
	
	// Indica se o socket com o nó principal esta ativo.
	bool flagSockConectado = false;

	// Sockets a serem manipulados.
	int sockfd = -1;
	int accfd = -1;
	int listenfd = -1;
	
	// Porta e ip do servidor principal.
	int portaConnect;
	char servidor[TAM_STR_IP + 1];
	
	// Ponteiro p/ argumentos.
	TpArgumento * argumentos;
	
	char maquina[MAX_CANON];
	
	//Variaveis necessarias para o uso de "select".
	//int	i;
	//int	maxi;
	int	nready;
	int	peerfd;			//Armazena temporariamente o descritor que estah sendo checado.

	// Inicializa variaveis.
	
	argumentos = (TpArgumento *)args;
	
	listenfd = argumentos->listenfd;
	portaConnect = argumentos->portaConnect; // Se for -1 eh pq eh um noh principal
	strcpy(servidor, argumentos->ipConnect); // Se for NULL eh pq eh um noh principal
	
	maxfd = listenfd;			// Valor inteiro do maior descritor utilizado. Inicialmente soh temos o listenfd
	//maxi = -1;
	
	FD_ZERO(&allset);		// Zera todos os bits do set de descritores que serao checados
	FD_SET(listenfd, &allset);	// Seta o bit do listenfd, ou seja, coloca listenfd no set de descritores q sera usado por "select"
	
	FD_SET(fileno(stdin), &allset);
	if(fileno(stdin) > maxfd)
		maxfd = fileno(stdin);	
	
	if(!DadosAplicacao.principal) {
	
		puts("Entrou como naum principal");
		
		while((sockfd = u_connect(portaConnect, servidor)) == -1) {
			sleep(1);
			puts("Tentando conectar no peer principal...");
		}
		
		DadosAplicacao.sockPrincipalConectado = sockfd;
		if(sockfd >= 0) {
				
				FD_SET(sockfd, &allset);		// Utiliza-se esse socket para falar com o noh principal	
				if(sockfd > maxfd)
					maxfd = sockfd;
				
				insereTabelaSocket(sockfd);
					
				flagSockConectado = true;
		}
		
	}
	
	// 'zSeta' os TIMER's.
	SetTimer( DadosAplicacao.intervaloHello, TIMER_HELLO, 0 );
	
	for(;;) {
		
		#ifdef DEBUG
		fprintf(stdout, "\nInicio do FOR\n");
		fprintf(stdout, "SockPrincipal: %d\n\n\n", DadosAplicacao.sockPrincipalConectado);
		#endif
		
		if(DadosAplicacao.principal && (DadosAplicacao.sockPrincipalConectado != -1) && (!flagSockConectado)) {
			
			sockfd = DadosAplicacao.sockPrincipalConectado;	
			
			if(sockfd >= 0) {
				
				FD_SET(sockfd, &allset);		// Utiliza-se esse socket para falar com o noh principal	
				if(sockfd > maxfd)
					maxfd = sockfd;
				
				insereTabelaSocket(sockfd);
					
				flagSockConectado = true;
			}
		}
		
		// Seta o conjunto de descritores que serah checado para eventos do tipo "read"
		rset = allset;
		
		#ifdef DEBUG
		if(RetornaTimer() == NULL)	fprintf(stdout, "Timer NULL\n");
		else	imprimeTimer();
		#endif
		
		//printf("\nANTES DO SELECT:\n");
		//printf("nready: %d\terrno: %d(%d)\n\n", nready, errno, EINTR);
		
		// Retorna o numero de sockets prontos ou zero caso seja um evento de timeout.
		while(((nready = select(maxfd + 1, &rset, NULL, NULL, RetornaTimer()) ) == -1) && (errno == EINTR));
		
		//printf("\n-----> SELECT <-----\n");
		
		// Caso select retorne -1 e o tipo de erro naum seja interrupcao
		if( nready == -1 ) {
			printf("\n-----> ERRO SELECT <-----\n");
			puts(strerror(errno));
			exit(1);
		}
		
		//*********************************
		// TRATA EVENTO DE TIMEOUT
		//*********************************
		
		if(nready == 0) {
//			printf("\n-----> TIMER <-----\n");
			#ifdef DEBUG
				puts("Vou chamar o trataTimer");
			#endif
			
			trataTimer();
		}
		
		//*********************************
		// TRATA PEDIDOS DE CONEXOES
		//*********************************
		
		if(FD_ISSET(listenfd, &rset))
		{
			printf("\n-----> CONEXAO <-----\n");
			//fprintf(stdout, "*** Listen ***\n");
			if((accfd = u_accept(listenfd, maquina)) >= 0)
			{
				puts("Conectou");
				insereTabelaSocket(accfd);
			}
			else{
					// TODO  Accept deu erro - TRATAR
			}
			
			FD_SET(accfd, &allset); 	// Seta o bit para o novo descritor no set de descritores q estao sendo tratados por "select"
			
			if(accfd > maxfd)
				maxfd = accfd;  		// Variavel q sera utilizada na chamada a "select"
			
			if(--nready <= 0)		// Caso o unico descritor setado for o listenfd
				continue;				// Nao ha mais descritores pendentes de serem tratados
		}
		
		
		//**********************************
		// TRATA EVENTOS DE TECLADO
		//**********************************
		
		if( FD_ISSET( fileno(stdin), &rset ) ) {
			printf("\n-----> TECLADO <-----\n");
			
			fprintf(stdout, "*** Teclado ***\n");
			readCmdLine();
		}
		
		//***********************************
		// TRATA RECEBIMENTO DE MENSAGENS
		//***********************************
		
		if((peerfd = encontraTabelaSocketPorRSet(rset)) != -1) {

			//#ifdef DEBUG
	//			printf("\n-----> MENSAGEM <-----\n");
		//		printf("Socket: %d\n", peerfd);
			//#endif
									
			trataRecebimento(peerfd);
			
			if (--nready <= 0 )
				continue;
		}
	}
}