C++ UDP通信Demo

UDP监听端:

#include "stdafx.h"
#include
#include

#pragma comment(lib,"WS2_32.lib")
using namespace std;


WSADATA wsaData;//初始化
SOCKET RecvSocket;
sockaddr_in RecvAddr;//服务器地址
int Port=5525;//服务器监听地址
char RecvBuf[1024];//发送数据的缓冲区
int BufLen=1024;//缓冲区大小
sockaddr_in SenderAddr;
int SenderAddrSize;

void UDPRecieve()
{
	//调用Recvfrom函数在绑定的socket上接收数据
	
	recvfrom(RecvSocket,RecvBuf,BufLen,0,(SOCKADDR *)&SenderAddr,&SenderAddrSize);
	printf("receiving data=== %s\n",RecvBuf);

}

void CloseUDP()
{
	//关闭socket,结束接收数据
	printf("finished receiving,closing socket..\n");
	closesocket(RecvSocket);
	//释放资源,退出
	printf("Exiting.\n");
	WSACleanup();
}


int _tmain(int argc, _TCHAR* argv[])
{
	SenderAddrSize=sizeof(SenderAddr);
	//初始化Socket
	WSAStartup(MAKEWORD(2,2),&wsaData);
	//创建接收数据报的socket
	RecvSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	//将socket与制定端口和0.0.0.0绑定
	RecvAddr.sin_family=AF_INET;
	RecvAddr.sin_port=htons(Port);
	RecvAddr.sin_addr.s_addr=htonl(INADDR_ANY);
	bind(RecvSocket,(SOCKADDR *)&RecvAddr,sizeof(RecvAddr));

	while(1)
	{
		UDPRecieve();
	}

	return 0;
}

 

UDP发送端:

#include "StdAfx.h"
#include "UDPSend.h"


//#pragma comment(lib,"WS2_32.lib")

using namespace std;



WSADATA wsaData;//初始化
SOCKET SendSocket;
sockaddr_in RecvAddr;//服务器地址
int Port=5525;//服务器监听地址
char SendBuf[1024];//发送数据的缓冲区
int BufLen=1024;//缓冲区大小

UDPSend::UDPSend()
{

	//初始化Socket
	WSAStartup(MAKEWORD(2,2),&wsaData);
	//创建Socket对象
	SendSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	//设置服务器地址
	RecvAddr.sin_family=AF_INET;
	RecvAddr.sin_port=htons(Port);
	RecvAddr.sin_addr.s_addr=inet_addr("192.168.1.110");
	//向服务器发送数据报
	//printf("Sending a datagram to the receiver...\n");
	//sendto(SendSocket,SendBuf,BufLen,0,(SOCKADDR *)&RecvAddr,sizeof(RecvAddr));
	//发送完成,关闭Socket
	//printf("finished sending,close socket.\n");
	//closesocket(SendSocket);
	/*printf("Exting.\n");
	WSACleanup();*/
	/*return 0;	*/
}

void UDPSend::SendData(char* lpFrame,int length)
{
	//byte buffer[1024];
	printf("Sending data====%s\n",lpFrame);

	sendto(SendSocket,lpFrame,BufLen,0,(SOCKADDR *)&RecvAddr,sizeof(RecvAddr));
}

void UDPSend::Close()
{
	printf("finished sending,close socket.\n");
	closesocket(SendSocket);
	printf("Exting.\n");
	WSACleanup();
}
#include

#include

class UDPSend
{
public:
	UDPSend();
	~UDPSend();

	void SendData(char* lpFrame,int length);
	void Close();
};

发送端在主控制台调用如下:

UDPSend* udpsend=new UDPSend();

while (1)
{

string str;

getline(cin,str);

udpsend->SendData((char*)(str.data()),1024);

}

你可能感兴趣的:(C++)