#include <winsock2.h>
#include <process.h>
#pragma comment(lib,"ws2_32.lib")
#pragma once
class CAsyncHandler
{
public:
CAsyncHandler()
{
}
virtual ~CAsyncHandler()
{
}
virtual int AcceptNotify( SOCKET hSocket, const char *strClientIP, unsigned short usClientPort )= 0;
};
class CAsynch_Event_Handler
{
public:
CAsynch_Event_Handler(void);
~CAsynch_Event_Handler(void);
int Start(CAsyncHandler * phEvent, UINT unPort);
int Stop(void);
protected:
static unsigned int __stdcall AcceptThread(void * lpParam);
unsigned int AcceptThreadProc();
private:
SOCKET m_hListenSocket;
HANDLE m_hIOThread;
HANDLE m_hExitThread;
CAsyncHandler *m_pEventHandler;
private:
int OnAccept();
BOOL InitSocket()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
/* Tell the user that we could not find a usable */
/* WinSock DLL.
*/
return FALSE;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )
{
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return FALSE;
}
return TRUE;
};
BOOL ClearSocket()
{
WSACleanup( );
return TRUE;
};
};
///*************** CPP*****************//
#include "StdAfx.h"
#include "Asynch_Event_Handler.h"
#include <iostream>
using namespace std;
CAsynch_Event_Handler::CAsynch_Event_Handler(void)
{
m_hListenSocket = INVALID_SOCKET;
}
CAsynch_Event_Handler::~CAsynch_Event_Handler(void)
{
}
int CAsynch_Event_Handler::Start(CAsyncHandler * phEvent, UINT unPort)
{
if( m_hListenSocket != INVALID_SOCKET )
{
return 0;
}
InitSocket();
m_pEventHandler = phEvent;
struct sockaddr_in serverAddress;
int err;
m_hListenSocket = socket(AF_INET, SOCK_STREAM, 0);
if( INVALID_SOCKET == m_hListenSocket )
{
err = WSAGetLastError();
return err;
}
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = 0;
serverAddress.sin_port = htons( unPort );
err = bind(m_hListenSocket,
(struct sockaddr *)&serverAddress,
sizeof(serverAddress)
);
if( err == SOCKET_ERROR )
{
err = WSAGetLastError();
closesocket( m_hListenSocket );
m_hListenSocket = INVALID_SOCKET;
return err;
}
err = listen( m_hListenSocket, SOMAXCONN );
if( err == SOCKET_ERROR )
{
err = WSAGetLastError();
closesocket( m_hListenSocket );
m_hListenSocket = INVALID_SOCKET;
return err;
}