#pragma once
#include
#pragma comment(lib,"WS2_32.lib")
#define LOCAL_IP_ADDR INADDR_ANY //当前应用程序接收的IP地址
#define LOCAL_PORT 9527 //当前应用程序的端口
#define DEST_IP_ADDR "127.0.0.1" //目标应用程序的IP地址
#define DEST_PORT 9526 //目标应用程序的端口
class UDP
{
public:
UDP();
~UDP();
void setLocalSockAddr(unsigned long localAddr, const int localPort); //设置当前应用程序的IP地址和端口
void setDestSockAddr(const char* destAddr, const int destPort); //设置目标应用程序的IP地址和端口
int sendData(char* buf, int len);
int recvData(char* buf, int len);
private:
WSADATA m_wsaData;
SOCKET m_Socket;
sockaddr_in m_localSockAddr; //当前应用程序的sockaddr_in结构体
sockaddr_in m_destSockAddr; //目标应用程序的sockaddr_in结构体
};
#include "udp.h"
UDP::UDP()
{
WSAStartup(MAKEWORD(2, 2), &m_wsaData);
m_Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//将socket设为非阻塞模式
u_long mode = 1;
ioctlsocket(m_Socket, FIONBIO, &mode);
//设置当前程序和目标程序的配置
setLocalSockAddr(LOCAL_IP_ADDR, LOCAL_PORT);
setDestSockAddr(DEST_IP_ADDR, DEST_PORT);
}
UDP::~UDP()
{
closesocket(m_Socket);
WSACleanup();
}
//设置当前应用程序的IP地址和端口
void UDP::setLocalSockAddr(unsigned long localAddr, const int localPort)
{
//当前应用程序的配置
m_localSockAddr.sin_family = AF_INET;
m_localSockAddr.sin_addr.s_addr = htonl(localAddr);
m_localSockAddr.sin_port = htons(localPort);
//绑定当前应用程序套接字
bind(m_Socket, (SOCKADDR*)&m_localSockAddr, sizeof(m_localSockAddr));
}
//设置目标应用程序的IP地址和端口
void UDP::setDestSockAddr(const char * destAddr, const int destPort)
{
//目标应用程序的配置
m_destSockAddr.sin_family = AF_INET;
m_destSockAddr.sin_addr.s_addr = inet_addr(destAddr);
m_destSockAddr.sin_port = htons(destPort);
}
int UDP::sendData(char * buf, int len)
{
int ret = sendto(m_Socket, buf, len, 0, (SOCKADDR*)&m_destSockAddr, sizeof(m_destSockAddr));
return ret;
}
int UDP::recvData(char* buf, int len)
{
int sockAddrSize = sizeof(sockaddr_in);
int ret = recvfrom(m_Socket, buf, len, 0, (SOCKADDR*)&m_localSockAddr, &sockAddrSize);
return ret;
}
#include
#include "udp.h"
int main()
{
UDP udp;
while (1)
{
char buf[1024];
int ret = udp.recvData(buf, 1024);
if (ret > 0)
{
std::cout << "server recv: " << buf << std::endl;
}
else
{
std::cout << "server recv: " << "recv failed" << std::endl;
}
Sleep(1000);
}
return 0;
}
需要先将udp.h中宏定义的IP和端口修改一下
#define LOCAL_IP_ADDR INADDR_ANY //当前应用程序接收的IP地址
#define LOCAL_PORT 9527 //当前应用程序的端口
#define DEST_IP_ADDR "127.0.0.1" //目标应用程序的IP地址
#define DEST_PORT 9526 //目标应用程序的端口
#include
#include "udp.h"
int main()
{
UDP udp;
while (1)
{
char buf[1024] = "hello udp...";
udp.sendData(buf, 1024);
std::cout << "client send: " << buf << std::endl;
Sleep(1000);
}
return 0;
}