udptest.cpp

来自「网络通信模块。开发包的使用者需要自行承担使用本开发包的风险」· C++ 代码 · 共 138 行

CPP
138
字号
// udpTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "udpTest.h"
#include "afxsock.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;
using namespace commIPC;


void showE(void)
{
	LPVOID lpMsgBuf;
	FormatMessage( 
		FORMAT_MESSAGE_ALLOCATE_BUFFER | 
		FORMAT_MESSAGE_FROM_SYSTEM | 
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL 
		);
	// Process any inserts in lpMsgBuf.
	// ...
	// Display the string.
	//MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
	// Free the buffer.
	printf("\t%s\n",lpMsgBuf);
	LocalFree( lpMsgBuf );
}
void doSendTest(LPCSTR pszIP)
{
	SOCKET sock=CUDPSocket::CreateUDPSocket(22222);

	char szB[102]="12345";
	char szHost[30];
	int iP;
	CUDPSocket s2(sock,TRUE);
	while(1)
	{
		int iRet,iSent,iRecv;
		iRet = s2.SendTo(32,(BYTE*)szB,iSent,pszIP,1024);
		if(iRet != 0)
			showE();
		printf("send %d %d\n",iRet,iSent);

		int iTest = s2.TestRead(2);
		if(iTest !=SP_ERR_SUCCESS)
		{
			cout<<"no echo data"<<endl;
			continue;
		}
		iRet = s2.RecvFrom(iSent,(BYTE*)szB,iRecv,szHost,&iP);
		//CString szSrc;
		//UINT iPort=1024;
		if(iRet != SP_ERR_SUCCESS)
			showE();
		else
			printf("recv %d %d %s %d\n",iRet,iRecv,szHost,iP);
		Sleep(500);
	}

}

void doRecvTest(void)
{
	SOCKET sock=CUDPSocket::CreateUDPSocket(1024);

	char szB[1024];
	CUDPSocket s2(sock,TRUE);
	
	//VERIFY(s2.Attach(sock));
	while(1)
	{
		int iTest = s2.TestRead(5);
		if(iTest !=SP_ERR_SUCCESS)
		{
			cout<<"no data"<<endl;
			continue;
		}
		char szHost[30];
		int iP,iRecv,iSent;
		int iRet = s2.RecvFrom(102,(BYTE*)szB,iRecv,szHost,&iP);
		//CString szSrc;
		//UINT iPort=1024;
		if(iRet != SP_ERR_SUCCESS)
			showE();
		printf("recv %d %d %s %d\n",iRet,iRecv,szHost,iP);
		iRet = s2.SendTo(iRecv,(BYTE*)szB,iSent,szHost,iP);
		if(iRet != 0)
			showE();
		printf("echo %d %d\n",iRet,iSent);

		Sleep(500);
	}
}

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

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		cerr << _T("Fatal Error: MFC initialization failed") << endl;
		nRetCode = 1;
		return 1;
	}
	AfxSocketInit();

	cout<<"发送:udpTest 192.168.0.1"<<endl;
	cout<<"接收:udpTest"<<endl;
	bool fSend=false;
	if(argc>=2)
		doSendTest(argv[1]);
	else
		doRecvTest();
	return nRetCode;
}


⌨️ 快捷键说明

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