You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
1.9 KiB
C++
100 lines
1.9 KiB
C++
#include "stdafx.h"
|
|
#include "CUDPSocket.h"
|
|
#ifdef _DEBUG
|
|
#define new DEBUG_NEW
|
|
#endif
|
|
|
|
CUDPSocket::CUDPSocket() : CAsyncSocket(), RemoteIP( "127.0.0.1" ), RemotePort( 8888 ),
|
|
LocalIP( "127.0.0.1" ), LocalPort(8889), SendHDNum( 0 ),
|
|
m_Param(NULL),RevData(NULL),
|
|
ReceiveNum( 0 ), bRecSearchHead( false ),m_Length( -1 )
|
|
{
|
|
memset(ReceiveBuf, 0, MAX_UDP_BUF_LEN);
|
|
}
|
|
|
|
void CUDPSocket::SetParams(CString localIP,unsigned int localPort,CString remoteIP,unsigned int remotePort)
|
|
{
|
|
memset(ReceiveBuf, 0, MAX_UDP_BUF_LEN);
|
|
LocalIP = localIP;
|
|
LocalPort = localPort;
|
|
RemoteIP = remoteIP;
|
|
RemotePort = remotePort;
|
|
}
|
|
|
|
CUDPSocket::~CUDPSocket()
|
|
{
|
|
try
|
|
{
|
|
CAsyncSocket::Close();
|
|
m_Param = NULL;
|
|
}
|
|
catch ( ... )
|
|
{
|
|
}
|
|
}
|
|
|
|
bool CUDPSocket::StartListening(bool flag)
|
|
{
|
|
RemoteIP.ReleaseBuffer();
|
|
LocalIP.ReleaseBuffer();
|
|
|
|
if ( !AfxSocketInit() )
|
|
{
|
|
return false;
|
|
}
|
|
if(flag)
|
|
{
|
|
if ( !Create( LocalPort, SOCK_DGRAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE ) )
|
|
{
|
|
return false;
|
|
}
|
|
|
|
Bind(LocalPort,LocalIP);
|
|
}
|
|
else
|
|
{
|
|
if ( !Create( LocalPort, SOCK_DGRAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,LocalIP ) )
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
|
|
DWORD dwFlag = 0;
|
|
IOCtl( FIONBIO, &dwFlag );
|
|
|
|
return true;
|
|
}
|
|
|
|
bool CUDPSocket::WriteBuffer( const void *buf, unsigned int len )
|
|
{
|
|
if(SendTo( buf, len, RemotePort, RemoteIP ) < 0)
|
|
{
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void CUDPSocket::OnReceive( int nErrorCode )
|
|
{
|
|
m_Length = ReceiveFrom( ReceiveBuf, MAX_UDP_BUF_LEN, RemoteIP, RemotePort );
|
|
if ( m_Length == SOCKET_ERROR )
|
|
{
|
|
return;
|
|
}
|
|
if ( RevData != NULL )
|
|
{
|
|
RevData(ReceiveBuf, m_Length, m_Param );
|
|
}
|
|
|
|
CAsyncSocket::OnReceive( nErrorCode );
|
|
}
|
|
|
|
void CUDPSocket::SetCallBack( UDPRevDataCALLBACK DataCallBack, LPVOID Param )
|
|
{
|
|
|
|
m_Param = Param;
|
|
RevData = DataCallBack;
|
|
|
|
}
|