c++使用winsocket建立UDP

UDPServer.cpp
#include<WINSOCK2.H>
#include<iostream>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
int main()
{
WSADATA wsaData;//初始化
SOCKET SendSocket;
sockaddr_in RecvAddr;//服務器地址
int Port=4000;//服務器監聽地址
char SendBuf[1024];//發送數據的緩衝區
int BufLen=1024;//緩衝區大小
//初始化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.137.1");
//向服務器發送數據報
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;
}
UDPClient.cpp
#include<WINSOCK2.H>
#include<iostream>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
int main()
{
WSADATA wsaData;//初始化
SOCKET RecvSocket;
sockaddr_in RecvAddr;//服務器地址
int Port=4000;//服務器監聽地址
char RecvBuf[1024];//發送數據的緩衝區
int BufLen=1024;//緩衝區大小
sockaddr_in SenderAddr;
int 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));
//調用Recvfrom函數在綁定的socket上接收數據
printf("receiving datagrams...\n");
recvfrom(RecvSocket,RecvBuf,BufLen,0,(SOCKADDR *)&SenderAddr,&SenderAddrSize);
//關閉socket,結束接收數據
printf("finished receiving,closing socket..\n");
closesocket(RecvSocket);
//釋放資源,退出
printf("Exiting.\n");
WSACleanup();
return 0;
}
相關文章
相關標籤/搜索