コード例 #1
0
ファイル: StarShape.cpp プロジェクト: noriter/wxWidgets
void cStarShape::Initialize()
{
    // initialize custom data members...
    m_sDescription = wxT("Insert some shape's description text here...");
    // now tell the serializer that this data member should be serialized
    // (see library documentation to get more info about available serialization
    // macros (supported data types))
    XS_SERIALIZE(m_sDescription, wxT("description"));

    // polygon-based shapes can be connected either to the vertices or to the
    // nearest border point (default value is TRUE).
    SetConnectToVertex(false);

    // set accepted connections for the new shape
    AcceptConnection(wxT("All"));
    AcceptSrcNeighbour(wxT("cStarShape"));
    AcceptTrgNeighbour(wxT("cStarShape"));

	// create associated shape(s)
	m_pText = new wxSFEditTextShape();
    // set some properties
    if(m_pText)
    {
        // set text
        m_pText->SetText(wxT("Hello!"));

        // set alignment
        m_pText->SetVAlign(wxSFShapeBase::valignMIDDLE);
        m_pText->SetHAlign(wxSFShapeBase::halignCENTER);

        // set required shape style(s)
		m_pText->SetStyle(sfsALWAYS_INSIDE | sfsHOVERING | sfsPROCESS_DEL | sfsPROPAGATE_DRAGGING | sfsPROPAGATE_SELECTION);
		// you can also force displaying of the shapes handles even if the interactive
		// size change is not allowed:
		//m_pText->AddStyle(sfsSHOW_HANDLES);

        // components of composite shapes created at runtime in parent shape's
        // constructor cannot be fully serialized (it means created by
		// the serializer) so it is important to disable their standard serialization
        // but they can be still serialized as the parent shape's properties 
		// in the standard way by the following macro:
		SF_ADD_COMPONENT( m_pText, wxT("title") );
    }
}
コード例 #2
0
Socket* TCPSocket::accept() {
    if (endPoint != LISTENER)
        return NULL;

    SOCKET client;

    client = AcceptConnection(sock);

    if (client == -1)
        return NULL;

    TCPSocket* tcpClient = new TCPSocket(SERVER);
    if (!tcpClient->setFD(client)) {
        delete tcpClient;
        return NULL;
    }

    return tcpClient;
}
コード例 #3
0
void CNetwork_Asio::AcceptConnection() {
  listener_.async_accept([this](std::error_code ec, tcp::socket socket) {
    if (!ec) {
      if (this->OnAccept())  // This should be changed to use a client session
      // instead of a CNetwork_Asio class
      {
        socket.non_blocking(true);
        // Do something here for the new connection.
        // Make sure to use std::move(socket)
        // std::make_shared<CClientSesson>( std::move(socket) );
        this->OnAccepted(std::move(socket));
      } else {
        // Kill the socket
        std::error_code ignored;
        socket.close(ignored);
      }
    }
    if (active_) AcceptConnection();
  });
}
コード例 #4
0
ファイル: threadloop.cpp プロジェクト: keenbo/abc
		int ThreadLoop::Loop()
		{
			while (1)
			{
				TimeTick();

				m_consumeMessage = 0;

				AcceptConnection(); 

				WaitConnection();

				ClearTimeoutSocket(); 
				
				if (0 == m_consumeMessage)
					m_epollMng.Wait(1); 

			}

			return 0;
		}
コード例 #5
0
void AFMServer::RunAsDaemon()
{
    bool r = Create(0, SOCK_STREAM, "EngineerModeServer"); //org "127.0.0.1" 37121
    if(!r)
    {
        EMSVRLOG("create server socket failure\n");
        return;
    }

    int rc = listen(m_hSocket, 5);
    if(rc)
    {
        EMSVRLOG("listen() fail; errno:%d, err_msg:%s\n", errno, strerror(errno));
        return;
    }

    m_bRunning = true;
    int failCount = 0;
    while (true)
    {
        if (!m_bRunning) {
            EMSVRLOG("EM SERVER exit Daemon\n");
            OnClose(failCount);
            break;
        }
        r = AcceptConnection();
        if (!r)
        {
            failCount++;
            EMSVRLOG("EM SERVER fail to listen connection\n");
        }
        if (failCount >= 5) {
            m_bRunning = false;
            EMSVRLOG("the fail count to listen connection is overflow the max count\n");
        }
    }
}
コード例 #6
0
Socket* SSLTCPSocket::accept() {
    if (endPoint != LISTENER)
        return NULL;

    SOCKET client;

    client = AcceptConnection(sock);

    if (client == -1 && !wouldBlock()) {
        setFatalError();
        return NULL;
    }
    else if (client == -1 && wouldBlock()) {
        return NULL;
    }

    SSLTCPSocket* sslClient = new SSLTCPSocket(SERVER);
    if (!sslClient->setFD(client)) {
        delete sslClient;
        return NULL;
    }

    return sslClient;
}
コード例 #7
0
ファイル: tcpserver.cpp プロジェクト: ArenaCloud/stunserver
void CTCPStunThread::Run()
{
    HRESULT hrPoll;
    
    Logging::LogMsg(LL_DEBUG, "Starting TCP listening thread (%d sockets)\n", _countSocks);
    
    _timeLastSweep = time(NULL);
    
    while (_fNeedToExit == false)
    {
        PollEvent pollevent = {};
        // wait for a notification
        int timeout = GetTimeoutSeconds();
        CStunSocket* pListenSocket = NULL;
        
        // turn off epoll eventing from the listen sockets if we are at max connections
        // otherwise, make sure it is enabled.
        SetListenSocketsOnEpoll(IsConnectionCountAtMax() == false);
        
        hrPoll = _spPolling->WaitForNextEvent(&pollevent, timeout);
        
        if ( _fNeedToExit || (pollevent.fd == _pipe[0]) )
        {
            break;
        }
        
        // hrPoll will be S_OK if there was an event.  S_FALSE otherwise
        ASSERT(SUCCEEDED(hrPoll));
        
        if (hrPoll == S_OK)
        {
            if (Logging::GetLogLevel() >= LL_VERBOSE)
            {
                Logging::LogMsg(LL_VERBOSE, "socket %d: %x (%s%s%s%s%s%s)", pollevent.fd, pollevent.eventflags,
                    (pollevent.eventflags&IPOLLING_READ) ? " IPOLLING_READ " : "",
                    (pollevent.eventflags&IPOLLING_WRITE) ? " IPOLLING_WRITE " : "",
                    (pollevent.eventflags&IPOLLING_RDHUP) ? " IPOLLING_RDHUP " : "",
                    (pollevent.eventflags&IPOLLING_HUP) ? " IPOLLING_HUP " : "",
                    (pollevent.eventflags&IPOLLING_ERROR) ? " IPOLLING_ERROR " : "",
                    (pollevent.eventflags&IPOLLING_PRI) ? " IPOLLING_PRI " : "");
            }
            
            pListenSocket = GetListenSocket(pollevent.fd);
            if (pListenSocket)
            {
                StunConnection* pConn = AcceptConnection(pListenSocket);
                
                // as an optimization - see if we can do a read on the new connection
                if (pConn)
                {
                    ReceiveBytesForConnection(pConn);
                }
            }
            else
            {
                ProcessConnectionEvent(pollevent.fd, pollevent.eventflags);
            }
        }
        
        // close any connection that we haven't heard from in a while
        SweepDeadConnections();
    }
    
    ThreadCleanup();
    
    Logging::LogMsg(LL_DEBUG, "TCP Thread exiting");
}
コード例 #8
0
ファイル: sxFtpClient.cpp プロジェクト: YeZhui/git_repository
/*数据连接
  入参:pPath - 服务器端文件
  	nType - connection modes
  	nMode - mode codes
  	pData - 数据连接后返回的netbuf结构
  出参:成功返回1,失败返回0
*/
int yCFtp::DataConnect (const char *pPath, int nType, int nMode, netbuf **pData, FILE *logfp, const char *filename)
{
	assert (m_pCtl);
	char pBuf[256];
	int nDir = 0;

	if ((pPath == NULL) && ((nType == FTPLIB_FILE_WRITE) || (nType == FTPLIB_FILE_READ)))
	{
		sprintf (m_pCtl->pResponse, "Missing path argument for file transfer\n");
		return 0;
	}

	sprintf (pBuf, "TYPE %c", nMode);

	if (!Sendcmd (pBuf, '2'))
	{
		if (NULL != logfp)
		{
			fprintf(logfp, "%s: Sendcmd (pBuf, 2) error!\n", filename);
		}
	
		return 0;
	}

	switch (nType)
	{
	case 1://FTPLIB_DIR
		strcpy (pBuf, "NLST");
		nDir = FTPLIB_READ;
		break;

	case 2://FTPLIB_DIR_VERBOSE:
		strcpy (pBuf, "LIST");
		nDir = FTPLIB_READ;
		break;

	case 3://FTPLIB_FILE_READ:
		strcpy (pBuf, "RETR");
		nDir = FTPLIB_READ;
		break;

	case 4://FTPLIB_FILE_WRITE:
		strcpy (pBuf, "STOR");
		nDir = FTPLIB_WRITE;
		break;

	default:
		sprintf (m_pCtl->pResponse, "Invalid open type %d\n", nType);
		return 0;
	}

	if (pPath)
	{
		int i = strlen (pBuf);
		pBuf[i++] = ' ';
		if ((strlen (pPath) + i) >= sizeof (pBuf))
			return 0;
		strcpy (&pBuf[i], pPath);
	}

	if (!OpenPort (pData, nMode, nDir))
	{
		if (NULL != logfp)
		{
			fprintf(logfp, "%s: OpenPort error!\n", filename);
		}
		return 0;
	}

	if (!Sendcmd (pBuf, '1'))
	{
		(*pData)->pCtrl = NULL;
		CloseData (*pData);
		*pData = NULL;

		if (NULL != logfp)
		{
			fprintf(logfp, "%s: Sendcmd (pBuf, 1) error!\n", filename);
		}
		
		return 0;
	}

	if (m_pCtl->nMode == FTPLIB_PORT)
	{
		if (!AcceptConnection (*pData))
		{
			CloseData (*pData);
			*pData = NULL;

			if (NULL != logfp)
			{
				fprintf(logfp, "%s: AcceptConnection error!\n", filename);
			}
			
			return 0;
		}
	}

/*
	if (NULL != logfp)
	{
		fprintf(logfp, "%s: DataConnect Successfully!\n", filename);
	}
*/

	return 1;
}
コード例 #9
0
ファイル: main_server.c プロジェクト: csmartins/SD2016-1
int main(int argc, char *argv[]) {
  TSocket srvSock, cliSock;        /* server and client sockets */
  struct TArgs *args;              /* argument structure for thread */
  pthread_t threads[NTHREADS];
  int tid = 0;
  fd_set set;  /* file description set */
  int ret, i;
  char str[BUFSIZE];

  if (argc == 1) { ExitWithError("Usage: server <local port>"); }

  /* Create a passive-mode listener endpoint */  
  srvSock = CreateServer(atoi(argv[1]));

  printf("Server read!\n");
  /* Run forever */
  for (;;) { 
    /* Initialize the file descriptor set */
    FD_ZERO(&set);
    /* Include stdin into the file descriptor set */
    FD_SET(STDIN_FILENO, &set);
    /* Include srvSock into the file descriptor set */
    FD_SET(srvSock, &set);

    /* Select returns 1 if input available, -1 if error */
    ret = select (FD_SETSIZE, &set, NULL, NULL, NULL);
    if (ret<0) {
       WriteError("select() failed"); 
       break;
    }

    /* Read from stdin */
    if (FD_ISSET(STDIN_FILENO, &set)) {
      scanf("%99[^\n]%*c", str);
      if (strncmp(str, "FIM", 3) == 0) {
        close(srvSock);
        break;
      }
    }

    /* Read from srvSock */
    if (FD_ISSET(srvSock, &set)) {
      if (tid == NTHREADS) { 
        WriteError("number of threads is over"); 
        break; 
      }
      
      /* Spawn off separate thread for each client */
      cliSock = AcceptConnection(srvSock);

      /* Create separate memory for client argument */
      if ((args = (struct TArgs *) malloc(sizeof(struct TArgs))) == NULL) { 
        WriteError("malloc() failed"); 
        break;
      }
      args->cliSock = cliSock;

      /* Create a new thread to handle the client requests */
      if (pthread_create(&threads[tid++], NULL, HandleRequest, (void *) args)) { 
        WriteError("pthread_create() failed"); 
      }
    }
  }
  
  printf("Server will wait for the active threads and terminate!\n");
  /* Wait for all threads to terminate */
  for(i=0; i<tid; i++) {
    pthread_join(threads[i], NULL);
  }
  return 0;
}
コード例 #10
0
ファイル: NMessageServer.cpp プロジェクト: x414e54/nano
//============================================================================
//		NMessageServer::ServerThread : Server thread.
//----------------------------------------------------------------------------
void NMessageServer::ServerThread(NSocket *theSocket)
{	NNetworkMessage			msgServerInfo, msgConnectRequest, msgConnectResponse;
	NStatus					theErr, acceptErr;
	NMessageHandshake		clientHandshake;
	NString					thePassword;
	NDictionary				serverInfo;
	bool					addClient;
	NEntityID				clientID;



	// Validate our state
	NN_ASSERT(mStatus == kNServerStarted);



	// Do the handshake
	theErr = ReadHandshake(theSocket, clientHandshake);

	if (theErr == kNoErr)
		theErr = WriteHandshake(theSocket, CreateHandshake());

	if (theErr == kNoErr)
		theErr = ValidateHandshake(clientHandshake);

	if (theErr != kNoErr)
		{
		theSocket->Close(theErr);
		return;
		}



	// Send the server info
	mLock.Lock();
	serverInfo    = GetConnectionInfo();
	msgServerInfo = CreateMessage(kNMessageServerInfoMsg, kNEntityEveryone);
	msgServerInfo.SetProperties(serverInfo);
	mLock.Unlock();

	theErr = WriteMessage(theSocket, msgServerInfo);
	if (theErr != kNoErr)
		{
		theSocket->Close(theErr);
		return;
		}



	// Read the connection request
	//
	// If the client does not wish to continue connecting, they will disconnect.
	theErr = ReadMessage(theSocket, msgConnectRequest);
	if (theErr != kNoErr)
		{
		theSocket->Close();
		return;
		}

	NN_ASSERT(msgConnectRequest.GetType()   == kNMessageConnectRequestMsg);
	NN_ASSERT(msgConnectRequest.GetSource() == kNEntityInvalid);



	// Accept the connection
	mLock.Lock();

	clientID  = GetNextClientID();
	acceptErr = AcceptConnection(serverInfo, msgConnectRequest.GetProperties(), clientID);

	msgConnectResponse = CreateMessage(kNMessageConnectResponseMsg, clientID);
	msgConnectResponse.SetValue(kNMessageStatusKey, acceptErr);

	theErr    = WriteMessage(theSocket, msgConnectResponse);
	addClient = (theErr == kNoErr && acceptErr == kNoErr);
	
	if (addClient)
		AddClient(clientID, theSocket);

	mLock.Unlock();

	if (!addClient)
		{
		theSocket->Close(theErr);
		return;
		}



	// Process messages
	ClientConnected(clientID);

	ProcessMessages(theSocket);
}
コード例 #11
0
ファイル: epserver.c プロジェクト: kefanchen/ckf-tcp
/*----------------------------------------------------------------------------*/
void *
RunServerThread(void *arg)
{
	int core = *(int *)arg;
	struct thread_context *ctx;
	mctx_t mctx;
	int listener;
	int ep;
	struct mtcp_epoll_event *events;
	int nevents;
	int i, ret;
	int do_accept;
	
	/* initialization */
	ctx = InitializeServerThread(core);
	if (!ctx) {
		TRACE_ERROR("Failed to initialize server thread.\n");
		return NULL;
	}
	mctx = ctx->mctx;
	ep = ctx->ep;

	events = (struct mtcp_epoll_event *)
			calloc(MAX_EVENTS, sizeof(struct mtcp_epoll_event));
	if (!events) {
		TRACE_ERROR("Failed to create event struct!\n");
		exit(-1);
	}

	listener = CreateListeningSocket(ctx);
	if (listener < 0) {
		TRACE_ERROR("Failed to create listening socket.\n");
		exit(-1);
	}

	while (!done[core]) {
		nevents = mtcp_epoll_wait(mctx, ep, events, MAX_EVENTS, -1);
		if (nevents < 0) {
			if (errno != EINTR)
				perror("mtcp_epoll_wait");
			break;
		}

		do_accept = FALSE;
		for (i = 0; i < nevents; i++) {

			if (events[i].data.sockid == listener) {
				/* if the event is for the listener, accept connection */
				do_accept = TRUE;

			} else if (events[i].events & MTCP_EPOLLERR) {
				int err;
				socklen_t len = sizeof(err);

				/* error on the connection */
				TRACE_APP("[CPU %d] Error on socket %d\n", 
						core, events[i].data.sockid);
				if (mtcp_getsockopt(mctx, events[i].data.sockid, 
						SOL_SOCKET, SO_ERROR, (void *)&err, &len) == 0) {
					if (err != ETIMEDOUT) {
						fprintf(stderr, "Error on socket %d: %s\n", 
								events[i].data.sockid, strerror(err));
					}
				} else {
					perror("mtcp_getsockopt");
				}
				CloseConnection(ctx, events[i].data.sockid, 
						&ctx->svars[events[i].data.sockid]);

			} else if (events[i].events & MTCP_EPOLLIN) {
				ret = HandleReadEvent(ctx, events[i].data.sockid, 
						&ctx->svars[events[i].data.sockid]);

				if (ret == 0) {
					/* connection closed by remote host */
					CloseConnection(ctx, events[i].data.sockid, 
							&ctx->svars[events[i].data.sockid]);
				} else if (ret < 0) {
					/* if not EAGAIN, it's an error */
					if (errno != EAGAIN) {
						CloseConnection(ctx, events[i].data.sockid, 
								&ctx->svars[events[i].data.sockid]);
					}
				}

			} else if (events[i].events & MTCP_EPOLLOUT) {
				struct server_vars *sv = &ctx->svars[events[i].data.sockid];
				if (sv->rspheader_sent) {
					SendUntilAvailable(ctx, events[i].data.sockid, sv);
				} else {
					TRACE_APP("Socket %d: Response header not sent yet.\n", 
							events[i].data.sockid);
				}

			} else {
				assert(0);
			}
		}

		/* if do_accept flag is set, accept connections */
		if (do_accept) {
			while (1) {
				ret = AcceptConnection(ctx, listener);
				if (ret < 0)
					break;
			}
		}

	}

	/* destroy mtcp context: this will kill the mtcp thread */
	mtcp_destroy_context(mctx);
	pthread_exit(NULL);

	return NULL;
}
コード例 #12
0
ファイル: hssocket.cpp プロジェクト: jrsteensen/hspace-old
bool CHSSocket::Process()
{
    fd_set fdReadSet;
    struct timeval timeout;
    int iSelectVal = 0;

    timeout.tv_sec = 0;
    timeout.tv_usec = 0;

    FD_ZERO(&fdReadSet);
    FD_SET(m_iSocket, &fdReadSet);

#ifdef WIN32
    if ((iSelectVal =
         select(1, &fdReadSet, NULL, NULL, (struct timeval *) &timeout)) < 0)
#else
    if ((iSelectVal =
         select(m_iSocket + 1, &fdReadSet, NULL, NULL,
                (struct timeval *) &timeout)) < 0)
#endif
    {
        // An error has occurred.  For now, just return false.
        return false;
    }
#ifdef WIN32
    else if ((iSelectVal == 1) && FD_ISSET(m_iSocket, &fdReadSet))
#else
    else if ((iSelectVal > 0) && FD_ISSET(m_iSocket, &fdReadSet))
#endif
    {
        // Our socket has something to read.
        if (m_bListenConnection)
        {
            // We have a new connection.  Accept it.
            if (!AcceptConnection())
            {
            }
        }
        else
        {
            // We're a normal data connection.

            // Allocate a buffer if needed.
            if (!m_pcReceivedBuffer)
            {
                m_pcReceivedBuffer = new char[HSCONST_MAX_RECEIVE];
                m_uiBytesPending = 0;
                m_uiBytesReceived = 0;
            }

            char *pCurPos = &(m_pcReceivedBuffer[m_uiBytesReceived]);
            unsigned int uiReceived;

            if ((uiReceived =
                 recv(m_iSocket, pCurPos,
                      HSCONST_MAX_RECEIVE - m_uiBytesReceived, 0)) <= 0)
            {
                if (m_pCloseCallback)
                {
                    m_pCloseCallback(this);
                }
                return false;   // Socket is shut down.
            }

            m_uiBytesReceived += uiReceived;

            // If we weren't expecting any data, determine how much we should receive.
            if (m_uiBytesPending == 0)
            {
                // Do we at least have enough data to decode the header size?
                if (uiReceived >= (int) sizeof(unsigned int))
                {
                    // Pull out the packet header.
                    m_uiBytesPending =
                        ntohl(*((unsigned int *) m_pcReceivedBuffer));

                    // Is this bigger than the allowed limit?
                    if (m_uiBytesPending > HSCONST_MAX_PACKETSIZE)
                    {
                        m_uiBytesPending = 0;
                        m_uiBytesReceived = 0;
                    }
                    else
                    {
                        // Double-check that the size specified corresponds to the data received.
                        if (m_uiBytesPending > uiReceived)
                        {
                            m_uiBytesPending = 0;
                            m_uiBytesReceived = 0;
                        }
                    }
                }
                else
                {
                    m_uiBytesReceived = 0;
                }
            }

            // Did we receive the data we were expecting?
            pCurPos = m_pcReceivedBuffer;
            while (m_uiBytesReceived
                   && (m_uiBytesReceived >= m_uiBytesPending))
            {
                // Skip over the size info.
                pCurPos += sizeof(unsigned int);

                // Call the receive callback, excluding the packet size.
                if (m_pReceiveCallback)
                {
                    m_pReceiveCallback(pCurPos,
                                       m_uiBytesPending -
                                       sizeof(unsigned int), this);
                }

                // Advance over this data.
                m_uiBytesReceived -= m_uiBytesPending;
                pCurPos += (m_uiBytesPending - sizeof(unsigned int));

                // No bytes pending that we know of.
                m_uiBytesPending = 0;

                // Is there more?
                if (m_uiBytesReceived > 0)
                {
                    // Do we at least have enough data to decode the header size?
                    if (m_uiBytesReceived >= sizeof(unsigned int))
                    {
                        // Pull out the packet header.
                        m_uiBytesPending = ntohl(*((unsigned int *) pCurPos));

                        // Is this bigger than the allowed limit?
                        if (m_uiBytesPending > HSCONST_MAX_PACKETSIZE)
                        {
                            m_uiBytesPending = 0;
                            m_uiBytesReceived = 0;
                        }
                        else
                        {
                            // Double-check that the size specified corresponds to the data received.
                            if (m_uiBytesPending > uiReceived)
                            {
                                m_uiBytesPending = 0;
                                m_uiBytesReceived = 0;
                            }
                        }
                    }
                    else
                    {
                        m_uiBytesPending = 0;
                        m_uiBytesReceived = 0;
                    }
                }
                else
                {
                    break;
                }
            }

            // If we processed any data, we need to move the remaining data to the beginning of the buffer.
            if ((pCurPos != m_pcReceivedBuffer) && (m_uiBytesPending > 0))
            {
                int iOffset = pCurPos - m_pcReceivedBuffer;
                int iLeftToRead = m_uiBytesReceived;

                while (iLeftToRead > 0)
                {
                    *(pCurPos - iOffset) = (*pCurPos)++;
                    iLeftToRead--;
                }
            }

            // At this point we should either have no data in receive buffer, not
            // enough data to determine the full packet type, or a partial packet
            // waiting for the rest to arrive.
        }
    }
    return true;
}
コード例 #13
0
void* rover_server_log(void* args)
{
  int retval, maxfd, num_fds;//, minfd, fddiff;
  char logbuf[k_LogBufSize];
  fd_set recv_set;
  struct timeval timeout;
  //const char* start_string = "logging started";

  //senders_ready = 0;
  // close(log_new_fd);
  // close(log_imu_new_fd1);
  // close(log_imu_new_fd2);  
  // close(log_imu_new_fd3);
  log_new_fd = -1;
  log_imu_new_fd1 = -1;
  //log_imu_new_fd2 = -1;
  //  log_imu_new_fd3 = -1;
  while (!log_thread_should_die)
    {//main accept() loop
      usleep(10000);
      // printf("At top of rover_server_log main accept loop"
      // 	     "log_new_fd = %d, log_sockfd = %d, "
      // 	     "log_imu_new_fd1 = %d, log_imu_new_fd2 = %d "
      //             "log_imu_new_fd3 = %d, log_imu_sockfd = %d\n",
      // 	     log_new_fd, log_sockfd, log_imu_new_fd1, log_imu_new_fd2,
      //             log_imu_new_fd3, log_imu_sockfd);
      /*
	AcceptConnection set to non-blocking, so will spin here until it either gets 
	a valid log_new_fd (and then goes into while loop below) or 
	log_thread_should_die becomes TRUE, which will cause the while loop 
	(and function) to exit.
       */
      if (!is_valid_fd(log_new_fd))
	{
	  log_new_fd = AcceptConnection(log_sockfd);
	  if (is_valid_fd(log_new_fd))
	    printf("Log connection established with log_sockfd = %d,"
		   "log_new_fd = %d\n", log_sockfd, log_new_fd);
	}
      if ((!is_valid_fd(log_imu_new_fd1)))
	{
	  log_imu_new_fd1 = AcceptConnection(log_imu_sockfd);
	  if (is_valid_fd(log_imu_new_fd1))
	    printf("IMU log connection #1 established with log_imu_sockfd = %d,"
		   "log_imu_new_fd1 = %d\n", log_imu_sockfd, log_imu_new_fd1);
	}

      // if ((!is_valid_fd(log_imu_new_fd2)))
      // 	{
      // 	  log_imu_new_fd2 = AcceptConnection(log_imu_sockfd);
      // 	  if (is_valid_fd(log_imu_new_fd2))
      // 	    printf("IMU log connection #2 established with log_imu_sockfd = %d,"
      // 		   "log_imu_new_fd2 = %d\n", log_imu_sockfd, log_imu_new_fd2);
      // 	}

      // if ((!is_valid_fd(log_imu_new_fd3)))
      // 	{
      // 	  log_imu_new_fd3 = AcceptConnection(log_imu_sockfd);
      // 	  if (is_valid_fd(log_imu_new_fd3))
      // 	    printf("IMU log connection #3 established with log_imu_sockfd = %d,"
      // 		   "log_imu_new_fd3 = %d\n", log_imu_sockfd, log_imu_new_fd3);
      // 	}

      if ((is_valid_fd(log_new_fd)) &&
	  (is_valid_fd(log_imu_new_fd1)))//  && 
	  // (is_valid_fd(log_imu_new_fd2)))
    //  &&
	  // (is_valid_fd(log_imu_new_fd3)))
    
	{
	  
	  //sort fds here 
	  int arr[3] = {log_new_fd, log_imu_new_fd1};//, log_imu_new_fd2};//, log_imu_new_fd3};
	  maxfd = arr[0];
	  for (int i = 0; i < 3; i++)
	    {
	      if (arr[i] > maxfd)
		maxfd = arr[i];
	    }
	  //printf("all fds valid, maxfd = %d\n", maxfd); 
	
	  while (!log_thread_should_die) 
	    {  
	      //*************CHECK FDS HERE****************
	      // printf("log_new_fd = %d, log_sockfd = %d\n", log_new_fd, log_sockfd);
	      // printf("log_imu_new_fd1 = %d, log_imu_sockfd = %d\n", 
	      // 	 log_imu_new_fd1, log_imu_sockfd);
	      memset(logbuf, 0, sizeof(logbuf));  //clear buffer
	      //wrapping recv in a select here to ensure loop checks 
	      //log_thread_should_die every timeout
	      FD_ZERO(&recv_set);
	      FD_SET(log_new_fd, &recv_set);
	      FD_SET(log_imu_new_fd1, &recv_set);
	      //FD_SET(log_imu_new_fd2, &recv_set);
	      //FD_SET(log_imu_new_fd3, &recv_set); 
	      timeout.tv_sec = 0;
	      timeout.tv_usec = 1000 * 10; //10ms timeout
	      //retval = select(log_new_fd+1, &recv_set, NULL, NULL, &timeout);
	      retval = select (maxfd + 1, &recv_set, NULL, NULL, &timeout);
	      if (retval < 0)
		perror("rover_server_log--select()");
	      //printf("select error\n");
	      else if (retval == 0) //timeout
		continue; //go back to the top of the loop and recheck log_thread_should_die
	      else //retval >= 1-->we have data to receive
		{
		  num_fds = retval; //this is the number of sockets with data ready
		  //first must see which socket received data
		  if (FD_ISSET(log_new_fd, &recv_set))
		    { //regular data log
		      if (!rover_server_recv_and_print(log_new_fd, log_file))
			break; //break if recv fails (due to error or remote shutdown)
		      //if we get here, we handled the message properly, so decrement
		      //num_fds and go back to top of loop if num_fds == 0
		      --num_fds;
		      if (num_fds == 0)
			continue;
		    }
		  else if (FD_ISSET(log_imu_new_fd1, &recv_set))
		    { //imu data log from 1st connection
		      if (!rover_server_recv_and_print(log_imu_new_fd1, imu_log_file))
			break; //break if recv fails (due to error or fd closure)
		      //if we get here, we handled the message properly, so decrement
		      //num_fds and go back to top of loop if num_fds == 0
		      --num_fds;
		      if (num_fds == 0)
			continue;
		    }
		  // else if (FD_ISSET(log_imu_new_fd2, &recv_set))
		  //   { //imu data log from 2nd connection
		  //     if (!rover_server_recv_and_print(log_imu_new_fd2, imu_log_file))
		  // 	break; //break if recv fails (due to error or fd closure)
		  //     //if we get here, we handled the message properly, so decrement
		  //     //num_fds and go back to top of loop if num_fds == 0
		  //     --num_fds;
		  //     if (num_fds == 0)
		  // 	continue;
		  //   }
		  // else if (FD_ISSET(log_imu_new_fd3, &recv_set))
		  //   { //imu data log from 3rd connection
		  //     // retval = recv(log_imu_new_fd3, &logbuf, sizeof(logbuf), 0);
		  //     // if (retval > 0) //received a valid message in logbuf
		  //     // 	{ //only log start message or if all 3 sensors have started
		  //     // 	  if (strstr(logbuf, start_string) != NULL)
		  //     // 	    {
		  //     // 	      fprintf(imu_log_file, "%s\n", logbuf);
		  //     // 	      senders_ready++;
		  //     // 	    }
		  //     // 	  else if (senders_ready == 3)
		  //     // 	    fprintf(imu_log_file, "%s\n", logbuf);
		  //     // 	}
		  //     // else if (retval < 0) //error
		  //     // 	{ //what error handling to do here??
		  //     // 	  printf("retval = %d\n", retval);
		  //     // 	  perror("rover_server_log:recv(imu_log_file)");
		  //     // 	  break;
		  //     // 	}
		  //     // else // retval == 0
		  //     // 	{//sender performed orderly shutdown, so don't print to log
		  //     // 	  close(log_imu_new_fd3);
		  //     // 	  break;
		  //     // 	}
		  //     if (!rover_server_recv_and_print(log_imu_new_fd3, imu_log_file))
		  // 	break; //break if recv fails (due to error or fd closure)
		  //     //if we get here, we handled the message properly, so decrement
		  //     //num_fds and go back to top of loop if num_fds == 0
		  //     --num_fds;
		  //     if (num_fds == 0)
		  // 	continue;
		  //   }
		  else //unknown fd in recv_set
		    {
		      printf("ERROR: rover_server_log(): unknown fd in recv_set\n");
		      break;
		    }
		}
	      //printf("at end of smaller loop\n");
	    }
	  //printf("at end of big if\n");
	}
      //printf("AT END OF MAIN LOOP\n");
    }
  //we only get here when log_thread_should_die is true
  //only close those that are still open, after waiting a bit
  usleep(100000);
  if (is_valid_fd(log_new_fd))
    close(log_new_fd);
  if (is_valid_fd(log_imu_new_fd1))
    close(log_imu_new_fd1);
  // if (is_valid_fd(log_imu_new_fd2))
  //   close(log_imu_new_fd2);
  // if(is_valid_fd(log_imu_new_fd3))
  //   close(log_imu_new_fd3); 
  return NULL;
}
コード例 #14
0
// functions not called from Scheme
void* rover_server_grab(void* args)
{
  struct CamGrab_t* my_args = (struct CamGrab_t*)args;
  int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
  int cdr_sockfd, cdr_new_fd; //for commander images
  int retval;
  char recvbuf[k_timestamp_len * 3];
  XEvent event;
  Display *display = XOpenDisplay(0);
  /* magic to get GUI to run periodically */
  event.type = KeyPress;
  event.xkey.keycode = 9;		/* ESC */
  event.xkey.state = 0;			/* no Mod1Mask */
  
  sockfd = StartServer(my_args->PortNumber);
  // cv::VideoWriter output_video;
  // cv::Size vid_size = cv::Size(640,480); //**HARDCODED** for 640x480 video
  // int codec = CV_FOURCC('M','J','P','G');
  // output_video.open(my_args->video_file_name, codec, 12.0, vid_size, true);
  printf("Opened video file %s\n", my_args->video_file_name);
  printf("server: waiting for image connection on port %s...\n",
	 my_args->PortNumber);
  cdr_sockfd = StartServer(my_args->CdrPortNumber);
  printf("server: waiting for commander image connection on port %s...\n", 
  	 my_args->CdrPortNumber);
  
  while(!grab_threads_should_die) 
    {  // main accept() loop
      usleep(10000);
      new_fd = AcceptConnection(sockfd);
      /*
	AcceptConnection set to non-blocking, so will spin here until it either gets 
	a valid new_fd (and then goes into while loop below) or 
	grab_threads_should_die becomes TRUE, which will cause the while loop 
	(and function) to exit.
       */
      if (new_fd != -1)
      	{
	  //receive and log start message into log file
      	  memset(recvbuf, 0 , sizeof(recvbuf));
      	  retval = recv(new_fd, &recvbuf, sizeof(recvbuf), 0);
      	  if (retval < 0)
      	    { //what error handling???
      	      printf("rover_server_grab recv retval = %d\n", retval);
      	    }
      	  else
      	    {
      	      fprintf(my_args->file_ptr, "%s\n", recvbuf);
      	      memset(recvbuf, 0 , sizeof(recvbuf));
      	    }
	  //try to connect to commander viewer
	  // cdr_sockfd = StartServer(my_args->CdrPortNumber);
	  // printf("server: waiting for commander image connection on port %s...\n", 
	  // 	 my_args->CdrPortNumber);
	  cdr_new_fd = AcceptConnection(cdr_sockfd);
	  if (cdr_new_fd != -1)
	    { //connection successful
	      cdr_viewer_active = TRUE;
	      printf("Commander viewer CONNECTED on port %s\n", my_args->CdrPortNumber);
	    }
	  else 
	    { //connection failed
	      cdr_viewer_active = FALSE;
	      printf("Commander image connection failed for port %s\n", my_args->CdrPortNumber);
	    }
      	}
      while(!grab_threads_should_die && (new_fd != -1))
	{
	  //here's where we do the magic
	  PointGrey_t2* PG = new PointGrey_t2;
	  PG->new_fd = new_fd;
	  PG->cdr_new_fd = cdr_new_fd;
	  Imlib_Image temp_img;
	  int working;
	  while (1)
	    {
	      if (OpenCV_ReceiveFrame(PG, my_args->file_ptr) != 0)
		{
		  close(PG->cdr_new_fd);
		  cdr_viewer_active = FALSE;
		  // printf("before close cdr_sockfd = %d\n", cdr_sockfd);
		  // close(cdr_sockfd);
		  // printf("after close cdr_sockfd = %d\n", cdr_sockfd);
		  break;
		}
	      //write frame to output video file
	      my_args->output_video->write(PG->uncompressedImage);
	      //send to commander viewer here??

	      //convert opencv to imlib for display in viewer
	      temp_img = Convert_OpenCV_to_Imlib(PG);
	      pthread_mutex_lock(&my_args->MostRecentLock);
	      working = ((my_args->MostRecent) + 1) % k_ImgBufSize;
	      pthread_mutex_unlock(&my_args->MostRecentLock);
	      pthread_mutex_lock(&my_args->ImgArrayLock[working]);
	      if (my_args->Set[working] == TRUE)
	      	{ //clean up memory allocation
	      	  imlib_context_set_image(*my_args->ImgArray[working]);
	      	  imlib_free_image_and_decache();
	      	}
	      else
		{
		  my_args->Set[working] = TRUE;
		}
	      *my_args->ImgArray[working] = temp_img;
	      pthread_mutex_unlock(&my_args->ImgArrayLock[working]);
	      pthread_mutex_lock(&my_args->MostRecentLock);
	      my_args->MostRecent = working;
	      pthread_mutex_unlock(&my_args->MostRecentLock);
	      XSendEvent(display, display_pane, FALSE, 0, &event);	      
	      XFlush(display);
	    }
	  delete PG;
	  printf("exiting from loop after AcceptConnection\n");
	  break;
	}
      if (new_fd != -1)
      	{//receive and log stop message into log file
      	  //memset(recvbuf, 0 , sizeof(recvbuf));
      	  retval = recv(new_fd, &recvbuf, sizeof(recvbuf), 0);
      	  if (retval <= 0)
      	    { //what error handling???
      	      printf("rover_server_grab recv (end) retval = %d\n", retval);
      	    }
      	  else
      	    fprintf(my_args->file_ptr, "%s\n", recvbuf);
      	}
      close(new_fd);  // accept loop doesn't need this
    }
  //do cleanup here
  close(sockfd);
  printf("sockfd closed\n");
  return NULL; 
}