1. 程式人生 > >C++ UDP通訊Demo

C++ UDP通訊Demo

UDP監聽端:

#include "stdafx.h"
#include<WINSOCK2.H>
#include<iostream>

#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<WINSOCK2.H>

#include<iostream>

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);

}