#include "stdafx.h" #include "CTCPSocket.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CTCPSocket::CTCPSocket() : CAsyncSocket(), RemoteIP( "127.0.0.1" ), RemotePort( 8888 ), LocalIP( "127.0.0.1" ), LocalPort(8889), RevData(NULL), m_Param( NULL ), m_Length( -1 ), m_bConnected( false ) { memset(ReceiveBuf, 0, MAX_TCP_BUF_LEN); } CTCPSocket::~CTCPSocket() { try { CAsyncSocket::Close(); m_Param = NULL; } catch ( ... ) { } } bool CTCPSocket::StartListening() { if ( !AfxSocketInit() ) { return false; } if ( !Create() ) { return false; } if ( Connect( RemoteIP, RemotePort )/*t_Error == 1*/) { //MessageBox(_T("Á¬½ÓTCP·þÎñÆ÷")+RemoteIP+_T("ʧ°Ü£¡")); return false; } return true; } bool CTCPSocket::WriteBuffer( const void *buf, unsigned int len ) { if(!m_bConnected) { return false; } int nRet = CAsyncSocket::Send( buf, len ); //Sleep( 1 ); if (SOCKET_ERROR == nRet) { return false; } return true; } void CTCPSocket::OnReceive( int nErrorCode ) { CAsyncSocket::OnReceive( nErrorCode ); if( nErrorCode == 0 ) { m_Length = ReceiveFrom( ReceiveBuf, MAX_TCP_BUF_LEN, RemoteIP, RemotePort ); if ( m_Length == SOCKET_ERROR ) { return; } if ( RevData != NULL ) { RevData(ReceiveBuf, m_Length, (UINT32)m_Param ); } } } void CTCPSocket::OnConnect(int nErrorCode) { if(nErrorCode == 0) { m_bConnected = true; } }