⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ttcp_dllhwsocket.cpp

📁 这里将 Socket APIs 封装成一个类似 CAsyncSocket 接口的类
💻 CPP
字号:
// TTCP_dllHwSocket.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "TTCP_dllHwSocket.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


#define WELCOME_STRING_TCP _T("Welcome to connect HWSocket TCP server\r\n")
#define RESPONSE_STRING_TCP _T("I am a TCP client\r\n")

// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

TCHAR* hwFormatMessage ( DWORD dwErrorCode )
{
	static TCHAR szError[256] = {0};
    FormatMessage (
		FORMAT_MESSAGE_FROM_SYSTEM,
		NULL,
		dwErrorCode,
		MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
		szError,
		COUNT(szError),
		NULL);
	return szError;
}

HANDLE m_hEvtEndModule = NULL;

//
// TCP 服务端
//
CHwSocket HwSocket_Listen, HwSocket_AcceptClient;
DWORD WINAPI Proc_TCPServer(
  LPVOID lpParameter   // thread data
)
{
	USES_CONVERSION;
	if ( !HwSocket_Listen.Create (2471) )
	{
		cout << "Create socket failed. " << T2A(hwFormatMessage(GetLastError())) << endl;
		return FALSE;
	}
	/*if ( !HwSocket_Listen.SetNonblocking () )
	{
		cout << "SetNonblocking socket failed. " << T2A(hwFormatMessage(GetLastError())) << endl;
		return FALSE;
	}*/
	if ( !HwSocket_Listen.Listen ( 5 ) )
	{
		cout << "Listen socket failed. " << T2A(hwFormatMessage(GetLastError())) << endl;
		return FALSE;
	}
	cout << "TCP server listen port 2471" << endl;

	BYTE szBuffer[1024] = {0};
	// 等待客户端连接
	while ( ::WaitForSingleObject ( m_hEvtEndModule, 0 ) != WAIT_OBJECT_0 )
	{
		if ( HwSocket_Listen.Accept ( HwSocket_AcceptClient ) )
		{
			cout << "New client [" << T2A(GetSocketAddressAndPort(HwSocket_AcceptClient)) << "] come in ..." << endl;
			HwSocket_AcceptClient.Send ( WELCOME_STRING_TCP, lstrlen(WELCOME_STRING_TCP)*sizeof(TCHAR) );
			int nRecvBytes = HwSocket_AcceptClient.Receive ( szBuffer, sizeof(szBuffer) );
			if ( nRecvBytes > 0 )
			{
				cout << "Server received data : " << T2A((LPCTSTR)szBuffer) << endl;
			}
			else
			{
				DWORD dwLastError = GetLastError();
				if ( (nRecvBytes == 0 && dwLastError != NO_ERROR) || (SOCKET_ERROR == nRecvBytes && dwLastError == WSAEWOULDBLOCK) )
				{
					cout << "None data for read" << endl;
				}
				else
				{
					cout << "Peer disconnect. " << T2A(hwFormatMessage(dwLastError)) << endl;
				}
			}
			HwSocket_AcceptClient.Close ();
		}
		else
		{
			if (GetLastError() == WSAEWOULDBLOCK)
			{
				Sleep ( 100 );
			}
			else
			{
				break;
			}
		}
	}

	cout << "Proc_TCPServer() thread exit" << endl;
	return TRUE;
}

//
// TCP 客户端
//
CHwSocket HwSocket_Connect;
DWORD WINAPI Proc_TCPClient(
  LPVOID lpParameter   // thread data
)
{
	USES_CONVERSION;

	// 等待客户端连接
	while ( ::WaitForSingleObject ( m_hEvtEndModule, 0 ) != WAIT_OBJECT_0 )
	{
		if ( !HwSocket_Connect.Create () )
		{
			cout << "Create socket failed. " << T2A(hwFormatMessage(GetLastError())) << endl;
			break;
		}

		if ( !HwSocket_Connect.Connect ( _T("127.0.0.1"), 2471 ) )
		{
			cout << "Connect TCP server failed. " << T2A(hwFormatMessage(GetLastError())) << endl;
			break;
		}
		Sleep ( 100 );
		cout << "Connect TCP server successfully ! My address is : " << T2A(GetSocketAddressAndPort(HwSocket_Connect)) << endl;

		BYTE szBuffer[1024] = {0};
		int nRecvBytes = HwSocket_Connect.Receive ( szBuffer, sizeof(szBuffer) );
		if ( nRecvBytes > 0 )
		{
			cout << "Client received data : " << T2A((LPCTSTR)szBuffer) << endl;
		}
		else
		{
			DWORD dwLastError = GetLastError();
			if ( (nRecvBytes == 0 && dwLastError != NO_ERROR) || (SOCKET_ERROR == nRecvBytes && dwLastError == WSAEWOULDBLOCK) )
			{
				cout << "None data for read" << endl;
			}
			else
			{
				cout << "Peer disconnect. " << T2A(hwFormatMessage(dwLastError)) << endl;
			}
		}

		HwSocket_Connect.Send ( RESPONSE_STRING_TCP, lstrlen(RESPONSE_STRING_TCP)*sizeof(TCHAR) );
		HwSocket_Connect.Close ();
		Sleep ( 1000 );
	}

	cout << "Proc_TCPClient() thread exit" << endl;
	return TRUE;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// 初始化 MFC 并在失败时显示错误
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: 更改错误代码以符合您的需要
		_tprintf(_T("错误: MFC 初始化失败\n"));
		nRetCode = 1;
	}
	else
	{
		cout << NOTE_CHwSocket << endl;
		WSADATA wsaData;
		if( WSAStartup( MAKEWORD(2,0), &wsaData) != 0)
			AfxMessageBox ( _T("WSAStartup() failed") );

		m_hEvtEndModule = ::CreateEvent ( NULL, TRUE, FALSE, NULL );
		CreateThread ( NULL, 0, ::Proc_TCPServer, NULL, 0, NULL );
		CreateThread ( NULL, 0, ::Proc_TCPClient, NULL, 0, NULL );
		
		cout << "System start OK. Press <ENTER> to exit ..." << endl;
		getchar ();

		SetEvent ( m_hEvtEndModule );
		HwSocket_Listen.Close ();
		HwSocket_AcceptClient.Close ();
		HwSocket_Connect.Close ();
		Sleep ( 2000 );

		WSACleanup();

		cout << "System end !" << endl;
		system ( "pause" );

	}

	return nRetCode;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -