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

📄 local.cpp

📁 UDP点对点通讯客户端和服务端
💻 CPP
字号:
// local.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "local.h"
#include "process.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;

unsigned int __stdcall WorkThread(void* param);

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;
	}
	else
	{
		// TODO: code your application's behavior here.
		CString strHello;
		strHello.LoadString(IDS_HELLO);
		cout << (LPCTSTR)strHello << endl;
	}

	WSADATA wsa;
	if(!AfxSocketInit(&wsa))
	{
		cout<<_T("socket init failed")<<endl;
	}
	_beginthreadex(NULL,0,WorkThread,NULL,0,NULL);
	while(getchar()!='e')
	{
		Sleep(5000);
	}
	return nRetCode;
}

unsigned int __stdcall WorkThread(void* param)
{
	SOCKET sock;
	sock=socket(AF_INET,SOCK_DGRAM,0);
	SOCKADDR_IN sin,saServ;
	int nSize=0;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(10002);
	sin.sin_addr.s_addr=htonl(INADDR_ANY);
	bind(sock,(SOCKADDR FAR*)&sin,sizeof(sin));

	saServ.sin_family=AF_INET;       
	saServ.sin_addr.s_addr=inet_addr("127.0.0.1");//IP地址自己改
	saServ.sin_port=htons(10002);
    nSize=sizeof(SOCKADDR_IN);
	char szBuf[10]={0};
	while(1)
	{
		recvfrom(sock,szBuf,10,0,(SOCKADDR*)&saServ,&nSize);
		sendto(sock,"abcdefghij",10,0,(SOCKADDR*)&saServ,sizeof(SOCKADDR_IN));
		printf("%s",szBuf);
		memset(szBuf,0,10);
		Sleep(5000);
	}
	return 0;
}

⌨️ 快捷键说明

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