示例#1
0
	bool CCommunication::Connect(CString sServerIP,DWORD nPort)
	{
		CAsyncSocket asConnect;

		if(!AfxSocketInit())
			return false;

		if(!asConnect.Create(0, SOCK_STREAM, NULL))
			return false;

		DWORD dwFlag = 0;

		ioctlsocket(asConnect.m_hSocket, FIONBIO, &dwFlag);

		if(!asConnect.Connect(sServerIP, nPort))
			return false;

		dwFlag=1;
		ioctlsocket(asConnect.m_hSocket, FIONBIO, &dwFlag);

		m_WorkSocket = asConnect.Detach();
		return true;
	}
示例#2
0
BOOL cNetworkPortController::LockPort(const UINT nPort, const int iFlags)
{
   m_strResult = "";
   
   m_bTcpResult = FALSE;
   m_bUdpResult = FALSE;
   m_strTcpResult = "";
   m_strUdpResult = "";
   
   if ( iFlags == NONE )
   {
      m_strResult = "No socket type specified";
      return FALSE;
   }
   else if ( iFlags > ALL )
   {
      m_strResult = "Invalid socket type specified";
      return FALSE;
   }
   
   CAsyncSocket *pSocket = NULL;
   CString strSocketType;
   CMapWordToOb *pMap = NULL;
   BOOL *pbResult = NULL;
   CString *pstrResult = NULL;

   int iSocketType;

   if ( iFlags & UDP )
   {
      strSocketType = "UDP";
      pMap = &m_mOpenUdpPorts;
      iSocketType = SOCK_DGRAM;
      pbResult = &m_bUdpResult;
      pstrResult = &m_strUdpResult;
   }
   else
   {
      strSocketType = "TCP";
      pMap = &m_mOpenTcpPorts;
      iSocketType = SOCK_STREAM;
      pbResult = &m_bTcpResult;
      pstrResult = &m_strTcpResult;
   }
   
   CString strTemp;

   while ( iSocketType )
   {     
      pSocket = new CAsyncSocket();

      // check for successfull construction socket
      if ( !AfxIsValidAddress( pSocket, 1, FALSE ) || pSocket <= 0 )
      {
         m_strResult = "Error while allocating memory";
         return FALSE;
      }

      // create the socket
      if ( !pSocket->Create( nPort, iSocketType, 0 ) )
      {
         DWORD dwErr = GetLastError();
         delete pSocket;

         if ( dwErr == WSAEADDRINUSE )
            *pstrResult = "In use by another app";
         else
            *pstrResult = "Not locked";

         return FALSE;
      }
      else
      {
         // save ptr to new socket for cleanup later
         pMap->SetAt( nPort, pSocket );

         *pbResult = TRUE;
         *pstrResult = "Locked";
      }

      if ( (iSocketType == SOCK_DGRAM) && (iFlags & TCP) )
      {
         iSocketType = SOCK_STREAM;
         pMap = &m_mOpenTcpPorts;
         pbResult = &m_bTcpResult;
         pstrResult = &m_strTcpResult;
      }
      else
      {
         iSocketType = 0;
         pMap = NULL;
         pbResult = NULL;
         pstrResult = NULL;
      }
   }
   
   return TRUE;
}