bool CSocket::DoPulse()
{
    // Make sure the socket exists before taking action
    if (m_pSocket != ERR_INVALID_SOCKET)
    {
        // Wait for connect to complete before proceeding
        if (!m_bConnected)
        {
            struct timeval tv = { 0, 0 };
            fd_set wfds;
            FD_ZERO(&wfds);
            FD_SET(m_pSocket, &wfds);
            // See if socket it writable
            int ret = select(m_pSocket+1, NULL, &wfds, NULL, &tv);
            if (ret == 0)
               return true;     // Not writable yet
            if (ret == -1)
               return false;    // select error
        }

        // Create a buffer for catching received data
        // (1 byte larger than receive limit, because another character has to be added)
        char chBuffer[SOCK_RECV_LIMIT + 1];

        // Receive the data
        int iLength = recv(m_pSocket, chBuffer, SOCK_RECV_LIMIT, 0);

        // Check if there were any errors
        int iError = GetLastSocketError();

        // Check if the socket just connected. If connection failed, return false
        if (!m_bConnected && (HandleConnection(iError) == ERR_CONNECT_FAILURE))
            return false;

        // If connected, handle data processing
        if (m_bConnected)
        {
            // Process data if there is any
            if (iLength > 0)
            {
                // Add a NULL at the end of the data, or the data will appear corrupted
                chBuffer[iLength] = '\0';

                TriggerEvent("onSockData",chBuffer);
            }
            else if (iError != ERR_NO_ERROR && iError != ERR_WOULD_BLOCK)
            {
                // An error has occured, so time to kill the socket
                m_bConnected = false;
                return false;
            }
        }
    }
    else
        // If the socket doesn't exist, well, error?
        return false;

    // If the call makes it up till here, it has been a huge success! Cake and true as a reward!
    return true;
}
示例#2
0
bool NetManager::Update()
{
	if (net_state_ == e_close)
	{
		return false;
	}

	if (!Select())
	{
		return false;
	}

	if (!HandleConnection())
	{
		return false;
	}

	std::map<int, OneConnectHelp *>::iterator it = connect_list_.begin();
	while (it != connect_list_.end())
	{
		if (!it->second->Update())
		{
			// 这里说明连接断开了
			connect_list_.erase(it++);
		}
		else
		{
			++it;
		}
	}
	return true;
}
示例#3
0
文件: server.c 项目: tzz/core
static void SpawnConnection(EvalContext *ctx, char *ipaddr, ConnectionInfo *info)
{
    ServerConnectionState *conn = NULL;
    int ret;
    pthread_t tid;
    pthread_attr_t threadattrs;

    conn = NewConn(ctx, info);
    int sd_accepted = ConnectionInfoSocket(info);
    strlcpy(conn->ipaddr, ipaddr, CF_MAX_IP_LEN );

    Log(LOG_LEVEL_VERBOSE, "New connection...(from %s, sd %d)",
        conn->ipaddr, sd_accepted);
    Log(LOG_LEVEL_VERBOSE, "Spawning new thread...");

    ret = pthread_attr_init(&threadattrs);
    if (ret != 0)
    {
        Log(LOG_LEVEL_ERR,
            "SpawnConnection: Unable to initialize thread attributes (%s)",
            GetErrorStr());
        goto err2;
    }
    ret = pthread_attr_setdetachstate(&threadattrs, PTHREAD_CREATE_DETACHED);
    if (ret != 0)
    {
        Log(LOG_LEVEL_ERR,
            "SpawnConnection: Unable to set thread to detached state (%s).",
            GetErrorStr());
        goto err1;
    }
    ret = pthread_attr_setstacksize(&threadattrs, 1024 * 1024);
    if (ret != 0)
    {
        Log(LOG_LEVEL_WARNING,
            "SpawnConnection: Unable to set thread stack size (%s).",
            GetErrorStr());
        /* Continue with default thread stack size. */
    }

    ret = pthread_create(&tid, &threadattrs,
                         (void *(*)(void *)) HandleConnection, conn);
    if (ret != 0)
    {
        errno = ret;
        Log(LOG_LEVEL_ERR,
            "Unable to spawn worker thread. (pthread_create: %s)",
            GetErrorStr());
        goto err1;
    }

  err1:
    pthread_attr_destroy(&threadattrs);
  err2:
    if (ret != 0)
    {
        Log(LOG_LEVEL_WARNING, "Thread is being handled from main loop!");
        HandleConnection(conn);
    }
}
示例#4
0
bool SimpleServer::run( ) //run a simple server
{
  bool succes = true;
  SOCKET clientSocket = INVALID_SOCKET; //initialize client socket descriptor
  try
  {
	  prepareServerSocket(); //create and bind server socket
	  
	  //Put socket into listening mode
	  if( listen( serverSocket, SOMAXCONN ) != 0 ) //begin listening
	  {
		  throw ServerResponseException("Cann't put socket into listening mode");
	  }

	  cout << "Waiting for connection ..." << endl;

	  sockaddr_in clientSockAddr;
	  int clientSockSize = sizeof(clientSockAddr);

	  clientSocket = accept(serverSocket ,reinterpret_cast<sockaddr*>(&clientSockAddr) ,&clientSockSize); //get the cliean socket
	  if ( clientSocket == INVALID_SOCKET )
	  {
		  throw ServerResponseException("Accept failed");
	  }

	  cout << "Accepted" << endl;
	  
	  HandleConnection(clientSocket,clientSockAddr); 
  }
  catch (ServerResponseException e)
  {
	  cerr << endl << "Error: " << e.what() << endl;
	  succes = false;
  }

  if( serverSocket != INVALID_SOCKET ) //close sockets
  {
	  closesocket(serverSocket);
  }

  if( clientSocket != INVALID_SOCKET )
  {
	  closesocket(clientSocket);
  }
}
示例#5
0
void WorldSocket::ProcessIncomingPacket(WorldPacket *recvPacket)
{
    uint16 msgCode = recvPacket->getMsgCode();

    switch (msgCode)
    {
        case MSG_CONNECTION:
        {
            HandleConnection(*recvPacket);
            break;
        }
        case MSG_PING:
        {
            HandlePing(*recvPacket);
            break;
        }
        case CMSG_AUTH_SESSION:
        {
            if (m_pSession)
            {
                cout << "Client try to auth again!" << endl;
                return;
            }
            HandleAuthSession(*recvPacket);
            break;
        }
        default:
        {
            if (m_pSession)
            {
                const MsgCodeHandler msghandler = msgCodeTable[msgCode];

                (m_pSession->*msghandler.handler)(*recvPacket);
            }
            else
                cout << "ERROR: Client not authed! Remote Host: " << getRemoteHost() << ", MsgCode: "<< msgCode << "(" << LookupMsgCodeName(msgCode) << ")" << endl;
        }
    }

    SAFE_DELETE(recvPacket);
}
FIOSInputInterface::FIOSInputInterface( const TSharedRef< FGenericApplicationMessageHandler >& InMessageHandler )
	: MessageHandler( InMessageHandler )
	, bAllowRemoteRotation(false)
	, bTreatRemoteAsSeparateController(false)
	, bUseRemoteAsVirtualJoystick(true)
	, bUseRemoteAbsoluteDpadValues(false)
{
#if !PLATFORM_TVOS
	MotionManager = nil;
	ReferenceAttitude = nil;
#endif

	GConfig->GetBool(TEXT("/Script/IOSRuntimeSettings.IOSRuntimeSettings"), TEXT("bTreatRemoteAsSeparateController"), bTreatRemoteAsSeparateController, GEngineIni);
	GConfig->GetBool(TEXT("/Script/IOSRuntimeSettings.IOSRuntimeSettings"), TEXT("bAllowRemoteRotation"), bAllowRemoteRotation, GEngineIni);
	GConfig->GetBool(TEXT("/Script/IOSRuntimeSettings.IOSRuntimeSettings"), TEXT("bUseRemoteAsVirtualJoystick"), bUseRemoteAsVirtualJoystick, GEngineIni);
	GConfig->GetBool(TEXT("/Script/IOSRuntimeSettings.IOSRuntimeSettings"), TEXT("bUseRemoteAbsoluteDpadValues"), bUseRemoteAbsoluteDpadValues, GEngineIni);

	
	[[NSNotificationCenter defaultCenter] addObserverForName:GCControllerDidConnectNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification* Notification)
	 {
		HandleConnection(Notification.object);
	 }];
示例#7
0
int
StartServer(const char *nssCertDBDir, SSLSNISocketConfig sniSocketConfig,
            void *sniSocketConfigArg)
{
  const char *debugLevel = PR_GetEnv("MOZ_TLS_SERVER_DEBUG_LEVEL");
  if (debugLevel) {
    int level = atoi(debugLevel);
    switch (level) {
      case DEBUG_ERRORS: gDebugLevel = DEBUG_ERRORS; break;
      case DEBUG_WARNINGS: gDebugLevel = DEBUG_WARNINGS; break;
      case DEBUG_VERBOSE: gDebugLevel = DEBUG_VERBOSE; break;
      default:
        PrintPRError("invalid MOZ_TLS_SERVER_DEBUG_LEVEL");
        return 1;
    }
  }

  const char *callbackPort = PR_GetEnv("MOZ_TLS_SERVER_CALLBACK_PORT");
  if (callbackPort) {
    gCallbackPort = atoi(callbackPort);
  }

  if (InitializeNSS(nssCertDBDir) != SECSuccess) {
    PR_fprintf(PR_STDERR, "InitializeNSS failed");
    return 1;
  }

  if (NSS_SetDomesticPolicy() != SECSuccess) {
    PrintPRError("NSS_SetDomesticPolicy failed");
    return 1;
  }

  if (SSL_ConfigServerSessionIDCache(0, 0, 0, nullptr) != SECSuccess) {
    PrintPRError("SSL_ConfigServerSessionIDCache failed");
    return 1;
  }

  UniquePRFileDesc serverSocket(PR_NewTCPSocket());
  if (!serverSocket) {
    PrintPRError("PR_NewTCPSocket failed");
    return 1;
  }

  PRSocketOptionData socketOption;
  socketOption.option = PR_SockOpt_Reuseaddr;
  socketOption.value.reuse_addr = true;
  PR_SetSocketOption(serverSocket.get(), &socketOption);

  PRNetAddr serverAddr;
  PR_InitializeNetAddr(PR_IpAddrLoopback, LISTEN_PORT, &serverAddr);
  if (PR_Bind(serverSocket.get(), &serverAddr) != PR_SUCCESS) {
    PrintPRError("PR_Bind failed");
    return 1;
  }

  if (PR_Listen(serverSocket.get(), 1) != PR_SUCCESS) {
    PrintPRError("PR_Listen failed");
    return 1;
  }

  UniquePRFileDesc rawModelSocket(PR_NewTCPSocket());
  if (!rawModelSocket) {
    PrintPRError("PR_NewTCPSocket failed for rawModelSocket");
    return 1;
  }

  UniquePRFileDesc modelSocket(SSL_ImportFD(nullptr, rawModelSocket.release()));
  if (!modelSocket) {
    PrintPRError("SSL_ImportFD of rawModelSocket failed");
    return 1;
  }

  if (SSL_SNISocketConfigHook(modelSocket.get(), sniSocketConfig,
                              sniSocketConfigArg) != SECSuccess) {
    PrintPRError("SSL_SNISocketConfigHook failed");
    return 1;
  }

  // We have to configure the server with a certificate, but it's not one
  // we're actually going to end up using. In the SNI callback, we pick
  // the right certificate for the connection.
  if (ConfigSecureServerWithNamedCert(modelSocket.get(), DEFAULT_CERT_NICKNAME,
                                      nullptr, nullptr) != SECSuccess) {
    return 1;
  }

  if (gCallbackPort != 0) {
    if (DoCallback()) {
      return 1;
    }
  }

  while (true) {
    PRNetAddr clientAddr;
    PRFileDesc* clientSocket = PR_Accept(serverSocket.get(), &clientAddr,
                                         PR_INTERVAL_NO_TIMEOUT);
    HandleConnection(clientSocket, modelSocket);
  }

  return 0;
}
示例#8
0
void DrawDepthMap(const xn::DepthMetaData& dmd, const xn::SceneMetaData& smd)
{
    static bool bInitialized = false;
    static GLuint depthTexID;
    static unsigned char* pDepthTexBuf;
    static int texWidth, texHeight;

    float topLeftX;
    float topLeftY;
    float bottomRightY;
    float bottomRightX;
    float texXpos;
    float texYpos;

    if(!bInitialized)
    {

        texWidth =  getClosestPowerOfTwo(dmd.XRes());
        texHeight = getClosestPowerOfTwo(dmd.YRes());

//		printf("Initializing depth texture: width = %d, height = %d\n", texWidth, texHeight);
        depthTexID = initTexture((void**)&pDepthTexBuf,texWidth, texHeight) ;

//		printf("Initialized depth texture: width = %d, height = %d\n", texWidth, texHeight);
        bInitialized = true;

        topLeftX = dmd.XRes();
        topLeftY = 0;
        bottomRightY = dmd.YRes();
        bottomRightX = 0;
        texXpos =(float)dmd.XRes()/texWidth;
        texYpos  =(float)dmd.YRes()/texHeight;

        memset(texcoords, 0, 8*sizeof(float));
        texcoords[0] = texXpos, texcoords[1] = texYpos, texcoords[2] = texXpos, texcoords[7] = texYpos;

    }
    unsigned int nValue = 0;
    unsigned int nHistValue = 0;
    unsigned int nIndex = 0;
    unsigned int nX = 0;
    unsigned int nY = 0;
    unsigned int nNumberOfPoints = 0;
    XnUInt16 g_nXRes = dmd.XRes();
    XnUInt16 g_nYRes = dmd.YRes();

    unsigned char* pDestImage = pDepthTexBuf;

    const XnDepthPixel* pDepth = dmd.Data();
    const XnLabel* pLabels = smd.Data();

    // Calculate the accumulative histogram
    memset(g_pDepthHist, 0, MAX_DEPTH*sizeof(float));
    for (nY=0; nY<g_nYRes; nY++)
    {
        for (nX=0; nX<g_nXRes; nX++)
        {
            nValue = *pDepth;

            if (nValue != 0)
            {
                g_pDepthHist[nValue]++;
                nNumberOfPoints++;
            }

            pDepth++;
        }
    }

    for (nIndex=1; nIndex<MAX_DEPTH; nIndex++)
    {
        g_pDepthHist[nIndex] += g_pDepthHist[nIndex-1];
    }
    if (nNumberOfPoints)
    {
        for (nIndex=1; nIndex<MAX_DEPTH; nIndex++)
        {
            g_pDepthHist[nIndex] = (unsigned int)(256 * (1.0f - (g_pDepthHist[nIndex] / nNumberOfPoints)));
        }
    }

    pDepth = dmd.Data();
    if (g_bDrawPixels)
    {
        XnUInt32 nIndex = 0;
        // Prepare the texture map
        for (nY=0; nY<g_nYRes; nY++)
        {
            for (nX=0; nX < g_nXRes; nX++, nIndex++)
            {

                pDestImage[0] = 0;
                pDestImage[1] = 0;
                pDestImage[2] = 0;
                if (g_bDrawBackground || *pLabels != 0)
                {
                    nValue = *pDepth;
                    XnLabel label = *pLabels;
                    XnUInt32 nColorID = label % nColors;
                    if (label == 0)
                    {
                        nColorID = nColors;
                    }

                    if (nValue != 0)
                    {
                        nHistValue = g_pDepthHist[nValue];

                        pDestImage[0] = nHistValue * Colors[nColorID][0];
                        pDestImage[1] = nHistValue * Colors[nColorID][1];
                        pDestImage[2] = nHistValue * Colors[nColorID][2];
                    }
                }

                pDepth++;
                pLabels++;
                pDestImage+=3;
            }

            pDestImage += (texWidth - g_nXRes) *3;
        }
    }
    else
    {
        xnOSMemSet(pDepthTexBuf, 0, 3*2*g_nXRes*g_nYRes);
    }

    glBindTexture(GL_TEXTURE_2D, depthTexID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, pDepthTexBuf);

    // Display the OpenGL texture map
    glColor4f(0.75,0.75,0.75,1);

    glEnable(GL_TEXTURE_2D);
    DrawTexture(dmd.XRes(),dmd.YRes(),0,0);
    glDisable(GL_TEXTURE_2D);

    char strLabel[50] = "";
    XnUserID aUsers[15];
    XnUInt16 nUsers = 15;
    g_UserGenerator.GetUsers(aUsers, nUsers);
    for (int i = 0; i < nUsers; ++i)
    {
#ifndef USE_GLES
        if (g_bPrintID)
        {
            XnPoint3D com;
            g_UserGenerator.GetCoM(aUsers[i], com);
            g_DepthGenerator.ConvertRealWorldToProjective(1, &com, &com);

            xnOSMemSet(strLabel, 0, sizeof(strLabel));
            if (!g_bPrintState)
            {
                // Tracking
                sprintf(strLabel, "%d", aUsers[i]);
            }
            else if (g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i]))
            {
                // Tracking
                sprintf(strLabel, "%d - Tracking", aUsers[i]);
            }
            else if (g_UserGenerator.GetSkeletonCap().IsCalibrating(aUsers[i]))
            {
                // Calibrating
                sprintf(strLabel, "%d - Calibrating [%s]", aUsers[i], GetCalibrationErrorString(m_Errors[aUsers[i]].first));
            }
            else
            {
                // Nothing
                sprintf(strLabel, "%d - Looking for pose [%s]", aUsers[i], GetPoseErrorString(m_Errors[aUsers[i]].second));
            }


            glColor4f(1-Colors[i%nColors][0], 1-Colors[i%nColors][1], 1-Colors[i%nColors][2], 1);

            glRasterPos2i(com.X, com.Y);
            glPrintString(GLUT_BITMAP_HELVETICA_18, strLabel);
        }
#endif
        if (g_bDrawSkeleton && g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i]))
        {
#ifndef USE_GLES
            glBegin(GL_LINES);
#endif
            glColor4f(1-Colors[aUsers[i]%nColors][0], 1-Colors[aUsers[i]%nColors][1], 1-Colors[aUsers[i]%nColors][2], 1);
            DrawLimb(aUsers[i], XN_SKEL_HEAD, XN_SKEL_NECK);

            DrawLimb(aUsers[i], XN_SKEL_NECK, XN_SKEL_LEFT_SHOULDER);
            DrawLimb(aUsers[i], XN_SKEL_LEFT_SHOULDER, XN_SKEL_LEFT_ELBOW);
            DrawLimb(aUsers[i], XN_SKEL_LEFT_ELBOW, XN_SKEL_LEFT_HAND);

            DrawLimb(aUsers[i], XN_SKEL_NECK, XN_SKEL_RIGHT_SHOULDER);
            DrawLimb(aUsers[i], XN_SKEL_RIGHT_SHOULDER, XN_SKEL_RIGHT_ELBOW);
            DrawLimb(aUsers[i], XN_SKEL_RIGHT_ELBOW, XN_SKEL_RIGHT_HAND);

            DrawLimb(aUsers[i], XN_SKEL_LEFT_SHOULDER, XN_SKEL_TORSO);
            DrawLimb(aUsers[i], XN_SKEL_RIGHT_SHOULDER, XN_SKEL_TORSO);

            DrawLimb(aUsers[i], XN_SKEL_TORSO, XN_SKEL_LEFT_HIP);
            DrawLimb(aUsers[i], XN_SKEL_LEFT_HIP, XN_SKEL_LEFT_KNEE);
            DrawLimb(aUsers[i], XN_SKEL_LEFT_KNEE, XN_SKEL_LEFT_FOOT);

            DrawLimb(aUsers[i], XN_SKEL_TORSO, XN_SKEL_RIGHT_HIP);
            DrawLimb(aUsers[i], XN_SKEL_RIGHT_HIP, XN_SKEL_RIGHT_KNEE);
            DrawLimb(aUsers[i], XN_SKEL_RIGHT_KNEE, XN_SKEL_RIGHT_FOOT);

            DrawLimb(aUsers[i], XN_SKEL_LEFT_HIP, XN_SKEL_RIGHT_HIP);


            //---------------- get skeleton data ----------------------

            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_HEAD, head);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_NECK, neck);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_TORSO, torso);

            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_LEFT_SHOULDER, leftShoulder);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_LEFT_ELBOW, leftElbow);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_LEFT_HAND, leftHand);

            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_RIGHT_SHOULDER, rightShoulder);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_RIGHT_ELBOW, rightElbow);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_RIGHT_HAND, rightHand);

            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_LEFT_HIP, leftHip);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_LEFT_KNEE, leftKnee);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_LEFT_FOOT, leftFoot);

            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_RIGHT_HIP, rightHip);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_RIGHT_KNEE, rightKnee);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i],
                    XN_SKEL_RIGHT_FOOT, rightFoot);

            //-------------- store frame data in frameData ------------
            char headX[30], headY[30], headZ[30], headC[30];
            strcpy(frameData, "");
            char space[2] = " ";

            sprintf(headX, "%f", head.position.X);
            sprintf(headY, "%f", head.position.Y);
            sprintf(headZ, "%f", head.position.Z);
            sprintf(headC, "%f", head.fConfidence);

            strcat(frameData, headX);
            strcat(frameData, space);
            strcat(frameData, headY);
            strcat(frameData, space);
            strcat(frameData, headZ);
            strcat(frameData, space);
            strcat(frameData, headC);
            strcat(frameData, space);

            //std::cout << "Frame data: " << frameData << std::endl;
            std::cout << "frameData to be sent: " << frameData << std::endl;
            HandleConnection(frameData);



            ////------- print to console -------
            //xnOSGetTimeStamp(&nNow);
            //nNow /= 1000;
            //std::cout << "-------------time: " << nNow << "---------------\n"
            //	<< "User " << aUsers[i] <<std::endl
            //	<< "	Head: " << head.position.X << " "
            //	<< head.position.Y << " " << head.position.Z
            //	<< head.fConfidence << std::endl;


#ifndef USE_GLES
            glEnd();
#endif
        }
    }
}