示例#1
0
void cNetworkPortController::ReleasePort(const UINT nPort, const int iFlags)
{
   CAsyncSocket *pSocket = NULL;

   if ( iFlags & UDP )
   {
      m_mOpenUdpPorts.Lookup( nPort, (CObject*&)pSocket );

      if ( pSocket > 0 )
      {
         pSocket->Close();
         delete pSocket;

         m_mOpenUdpPorts.RemoveKey( nPort );
      }
   }

   pSocket = NULL;

   if ( iFlags & TCP )
   {
      m_mOpenTcpPorts.Lookup( nPort, (CObject*&)pSocket );

      if ( pSocket > 0 )
      {
         pSocket->Close();
         delete pSocket;

         m_mOpenTcpPorts.RemoveKey( nPort );
      }
   }
}
示例#2
0
/*................无用...............*/
BOOL CWorkThread::Accept(CListenSocket& ListenSocket)
{
	CAsyncSocket asAccept;
	if(!ListenSocket.Accept(asAccept))
		return FALSE;

	CString strOut;
	strOut.Format(_T("CPoolThread::Accept() socket :%d Accept!\n"),asAccept.m_hSocket);
	TRACE(strOut);
	
	//线程池是否已满
	if(!WorkItem::IsPoolFull())
	{
		if(fpQueueUserWorkItem != NULL)
		{
			//
			fpQueueUserWorkItem(WorkItem::ClientWorkItemThread, (LPVOID)asAccept.Detach(), WT_EXECUTELONGFUNCTION);
		}
		else
		{
			//启动WorkItem类的ClientWorkThread线程
			AfxBeginThread(WorkItem::ClientWorkThread, (LPVOID)asAccept.Detach());
		}
	}
	else
	{
		// refuse request,close socket!拒绝客户端请求,关闭socket
		asAccept.Close();
	}

	return TRUE;
}
示例#3
0
文件: WySock.cpp 项目: trieck/source
void CWySock :: OnAccept(int nErrorCode)
{
    CWysApp* pApp = (CWysApp*)AfxGetApp();
    CWysWnd* pWnd = (CWysWnd*)pApp->m_pMainWnd;
    SCREENLINE sl;
    INT i;

    // make sure socket is listening
    if (this->State != LISTENING)
        return;

    if (nErrorCode == WSAENETDOWN) {
        sl.uColor = COLOR_RED;
        sl.szText.LoadString(GetLastError());
        pWnd->AddListItem(&sl);
        return;
    }

    // find a free socket
    if ((i = pApp->GetSocket()) == NOTFOUND) {
        // no space to accept this connection. however will accept
        // just using simple socket variable and close. Otherwise
        // client program will think it is connected.
        CAsyncSocket sdTemp;
        Accept(sdTemp, NULL,NULL);
        sdTemp.Close();
        sl.uColor = COLOR_RED;
        sl.szText.LoadString(IDS_NOMORESOCKETS);
        pWnd->AddListItem(&sl);
        return;
    }

    // accept the incoming connection
    SOCKADDR_IN		acc_sin;
    INT				acc_sin_len;
    CWySock* pSock	= pApp->pSockets[i];
    acc_sin_len		= sizeof(acc_sin);

    this->Accept(*pSock, (LPSOCKADDR)&acc_sin,
                 (LPINT)&acc_sin_len);

    if (pSock->m_hSocket == INVALID_SOCKET) {
        sl.uColor = COLOR_RED;
        sl.szText.LoadString(IDS_ACCEPTERR);
        pWnd->AddListItem(&sl);
        return;
    }

    CString szTemp;

    sl.uColor = COLOR_BLUE;
    szTemp.LoadString(IDS_ACCEPTCONNECT);
    strcpy(pSock->IPAddress, inet_ntoa(acc_sin.sin_addr));
    pSock->State = CONNECTED;
    sl.szText.Format(szTemp, pSock->IPAddress);
    pWnd->AddListItem(&sl);

    return;
}
示例#4
0
	BOOL CServerHandshake::RequestData(CAsyncSocket &socket, UINT nCount, clock_t clkDeadline)
	{
		while (true)
		{
			DWORD dwAvailable = 0;
			if (!socket.IOCtl(FIONREAD, &dwAvailable))
			{
				server.OnSocketError(socket.GetLastError());
				return FALSE;
			}
			if (dwAvailable >= nCount) return TRUE;
			if (clock() > clkDeadline) return FALSE;
		}
	}
示例#5
0
	BOOL CLANConnection::SendMessageTo(CAsyncSocket &socket, const CReference<CLANMessage> &msg,
		const BYTE *lpBuf, UINT nSize, SOCKADDR_IN *sockaddr)
	{
		clock_t deadline = clock() + SEND_TIMEOUT * CLOCKS_PER_SEC;

		// Nachricht versenden
		while (true)
		{
			int nCount = socket.SendTo(lpBuf, nSize, (SOCKADDR *)sockaddr, sizeof(*sockaddr));
			if (nCount == nSize)
			{
				if (m_pListener) m_pListener->OnMessageSent(msg, this);
			}
			else if (nCount == SOCKET_ERROR)
			{
				int nError = socket.GetLastError();

				if (nError == WSAEWOULDBLOCK)
				{
					Sleep(50);
					if (clock() <= deadline) continue;

					TRACE("LAN send timeout\n");
				}

				if (m_pListener)
				{
					m_pListener->OnSocketError(nError, this);
					m_pListener->OnMessageDiscarded(msg, this);
				}

				// bei Broadcast-Nachricht, deren Versenden aufgrund fehlender Verbindung zu einem lokalen
				// Netzwerk fehlschlug (WSAEHOSTUNREACH), den Thread nicht unterbrechen
				if (msg->GetReceiverIP() != INADDR_BROADCAST || nError != WSAEHOSTUNREACH)
				{
					__super::Interrupt();
					return FALSE;
				}
			}
			else
			{
				if (m_pListener) m_pListener->OnMessageDiscarded(msg, this);
			}

			break;
		}

		return TRUE;
	}
示例#6
0
void CListenPlayerSocket::OnAccept(int nErrorCode)
{
	// TODO: 在此添加专用代码和/或调用基类
	CAsyncSocket * pNewSock = new CPlayerTaskSocket;
	if(!Accept(*pNewSock))
	{
		delete pNewSock;
	}
	else
	{
		TRACE("%08x new connection\n", pNewSock);
		pNewSock->AsyncSelect(FD_READ);
		
	}
	CAsyncSocket::OnAccept(nErrorCode);
}
void DataSocket::OnAccept(int nErrorCode) 
{
	// Accept the connection using a temp CSocket object.
	CAsyncSocket tmpSocket;
	Accept(tmpSocket);
	
	SOCKET socket = tmpSocket.Detach();
	Close();

	Attach(socket);

	m_bConnected = TRUE;

	if (!m_bInitialized)
		SetTransferType(m_nTransferType);
	
	CAsyncSocket::OnAccept(nErrorCode);
}
示例#8
0
	BOOL CLANConnection::CreateSocket(int &nError)
	{
		nError = 0;
		if (m_hSocket != INVALID_SOCKET) return TRUE;

		// Socket erzeugen
		CAsyncSocket socket;
		if (!socket.Socket(SOCK_DGRAM, 0)) goto error;

/*		// mehrfaches Binden an selben Port erlauben
		BOOL bReuseAddr = TRUE;
		if (!socket.SetSockOpt(SO_REUSEADDR, &bReuseAddr, sizeof(bReuseAddr)))
			goto error; */

		// Socket binden
		if (!socket.Bind(m_nPort))	goto error;

		// Broadcast erlauben
		BOOL bBroadcast = TRUE;
		if (!socket.SetSockOpt(SO_BROADCAST, &bBroadcast, sizeof(bBroadcast)))
			goto error;

		m_hSocket = socket.Detach();
		return TRUE;

error:
		nError = socket.GetLastError();
		return FALSE;
	}
示例#9
0
void cNetworkPortController::ReleaseAllPorts(const int iFlags)
{
   POSITION Pos;
   CAsyncSocket *pSocket = NULL;
   unsigned short nPort = 0;

   if ( iFlags & UDP )
   {
      Pos = m_mOpenUdpPorts.GetStartPosition();

      while ( Pos )
      {
         m_mOpenUdpPorts.GetNextAssoc( Pos, nPort, (CObject*&)pSocket );
         
         if ( pSocket > 0 )
         {
            pSocket->Close();
            delete pSocket;
         }
      }
      m_mOpenUdpPorts.RemoveAll();
   }

   if ( iFlags & TCP )
   {
      Pos = m_mOpenTcpPorts.GetStartPosition();

      while ( Pos )
      {
         m_mOpenTcpPorts.GetNextAssoc( Pos, nPort, (CObject*&)pSocket );

         if ( pSocket > 0 )
         {
            pSocket->Close();
            delete pSocket;
         }
      }
      m_mOpenTcpPorts.RemoveAll();
   }
}
示例#10
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;
	}
示例#11
0
void PASCAL CAsyncSocket::DoCallBack(WPARAM wParam, LPARAM lParam)
{
	if (wParam == 0 && lParam == 0)
		return;

	// Has the socket be closed?
	CAsyncSocket* pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, TRUE);

	// If yes ignore message
	if (pSocket != NULL)
		return;

	pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, FALSE);
	if (pSocket == NULL)
	{
		// Must be in the middle of an Accept call
		pSocket = CAsyncSocket::LookupHandle(INVALID_SOCKET, FALSE);
		ASSERT(pSocket != NULL);
		pSocket->m_hSocket = (SOCKET)wParam;
		CAsyncSocket::DetachHandle(INVALID_SOCKET, FALSE);
		CAsyncSocket::AttachHandle(pSocket->m_hSocket, pSocket, FALSE);
	}

	int nErrorCode = WSAGETSELECTERROR(lParam);
	switch (WSAGETSELECTEVENT(lParam))
	{
	case FD_READ:
		pSocket->OnReceive(nErrorCode);
		break;
	case FD_WRITE:
		pSocket->OnSend(nErrorCode);
		break;
	case FD_OOB:
		pSocket->OnOutOfBandData(nErrorCode);
		break;
	case FD_ACCEPT:
		pSocket->OnAccept(nErrorCode);
		break;
	case FD_CONNECT:
		pSocket->OnConnect(nErrorCode);
		break;
	case FD_CLOSE:
		pSocket->OnClose(nErrorCode);
		break;
	}
}
示例#12
0
	void CLANConnection::Run()
	{
		VERIFY(AfxSocketInit());

		// Socket erzeugen, falls noch nicht geschehen
		int nError;
		if (!CreateSocket(nError))
		{
			if (m_pListener)
			{
				m_pListener->OnSocketError(nError, this);
				m_pListener->OnConnectionLost(this);
			}
			return;
		}

		CAsyncSocket socket;
		ASSERT(m_hSocket != INVALID_SOCKET);
		socket.Attach(m_hSocket);

		// IP-Adresse und tatsächlichen Port ermitteln
		SOCKADDR_IN sockaddr;
		memset(&sockaddr, 0, sizeof(sockaddr));
		int nSockAddrLen = sizeof(SOCKADDR_IN);
		if (!socket.GetSockName((SOCKADDR *)&sockaddr, &nSockAddrLen)) goto error;

		m_nPort = ntohs(sockaddr.sin_port);
		m_dwIP = ntohl(sockaddr.sin_addr.S_un.S_addr);

		// main thread loop
		BYTE buf[LAN_BUFSIZE];
		while (!IsInterrupted())
		{
			// Senden
			{
			CReference<CLANMessage> message;
			if (message = GetNextMessage())
			{
				// Magic Number
				memcpy(buf, "BotE", 4);

				// Nachricht serialisieren
				CMemFile memFile(&buf[4], LAN_BUFSIZE - 4);
				CArchive ar(&memFile, CArchive::store);
				message->Serialize(ar);
				ar.Close();
				UINT nSize = memFile.GetPosition() + 4;
				memFile.Detach();

				// Empfänger setzen
				memset(&sockaddr, 0, sizeof(sockaddr));
				sockaddr.sin_family = AF_INET;
				sockaddr.sin_addr.S_un.S_addr = htonl(message->GetReceiverIP());
				sockaddr.sin_port = htons(message->GetReceiverPort());

				// Nachricht versenden, setzt bei Fehler m_bInterrupted
				if (!SendMessageTo(socket, message, buf, nSize, &sockaddr)) break;

				// Broadcast-Nachricht auch an den lokalen Host senden
				if (message->GetReceiverIP() == INADDR_BROADCAST)
				{
					sockaddr.sin_addr.S_un.S_addr = htonl(INADDR_LOOPBACK);
					if (!SendMessageTo(socket, message, buf, nSize, &sockaddr))
						break;
				}
			}
			}

			// Empfangen
			memset(&sockaddr, 0, sizeof(sockaddr));
			int nSockAddrLen = sizeof(sockaddr);
			int nCount = socket.ReceiveFrom(&buf, LAN_BUFSIZE, (SOCKADDR *)&sockaddr, &nSockAddrLen);
			if (nCount > 0)
			{
				// Magic Number prüfen
				if (memcmp(&buf, "BotE", 4) != 0) continue;

				// Nachricht deserialisieren
				CMemFile memFile(&buf[4], nCount - 4);
				CArchive ar(&memFile, CArchive::load);
				CReference<CLANMessage> message(new CLANMessage());
				message->Serialize(ar);
				ar.Close();
				memFile.Detach();

				// IP und Port des Absenders
				DWORD dwIP = ntohl(sockaddr.sin_addr.S_un.S_addr);
				UINT nPort = ntohs(sockaddr.sin_port);
				message->SetSenderIP(dwIP);
				message->SetSenderPort(nPort);

				// Ankunft einer Nachricht melden
				if (m_pListener) m_pListener->OnMessageReceived(message, this);
			}
			else if (nCount == 0)
			{
				// "Verbindung" wurde getrennt
				ASSERT(FALSE);
				break;
			}
			else if (nCount == SOCKET_ERROR)
			{
				int nError = socket.GetLastError();
				if (nError != WSAEWOULDBLOCK)
				{
					if (m_pListener) m_pListener->OnSocketError(nError, this);
					// WSAECONNRESET tritt auf, wenn wir zuvor eine Nachricht an eine Adresse gesendet
					// haben, an der kein Server läuft; Thread dann nicht abbrechen
					if (nError != WSAECONNRESET)
					{
						__super::Interrupt();
						break;
					}
				}
			}

			Sleep(50);
		}

		// verbleibende Nachrichten löschen
		{
			CReference<CLANMessage> message;
			while (message = GetNextMessage())
			{
				if (m_pListener) m_pListener->OnMessageDiscarded(message, this);
			}
		}

		// socket schließen, Thread beenden
		socket.Close();
		m_hSocket = INVALID_SOCKET;
		if (m_bSendLost && m_pListener) m_pListener->OnConnectionLost(this);
		return;

error:
		if (m_pListener) m_pListener->OnSocketError(socket.GetLastError(), this);
		m_hSocket = INVALID_SOCKET;
		if (m_pListener) m_pListener->OnConnectionLost(this);
	}
示例#13
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;
}