C++ UDP C/S 简单封装(转载)

Server端类定义:
#include
#pragmacomment(lib, "ws2_32.lib")
 
class UDPServer{
private:
    WSADATA wsaData;
    SOCKET serverSocket;
    sockaddr_in serverSockAddr;
public:
    UDPServer();
    void setSockAddr(const char *destAddr,const int destPort);
    void listen(const int port);
    void receive() const;
    ~UDPServer();
};


 
Server端实现:
#include"UDPServer.h"
#include
 
using namespacestd;
 
UDPServer::UDPServer()
{
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    serverSocket = socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP);
    cout << "Server Socketinitialized" << endl;
}
 
voidUDPServer::listen(const int port)
{
    serverSockAddr.sin_family=AF_INET;
    serverSockAddr.sin_port=htons(port);
   serverSockAddr.sin_addr.s_addr=htonl(INADDR_ANY);
    bind(serverSocket, (SOCKADDR*)&serverSockAddr, sizeof(serverSockAddr));
}
 
voidUDPServer::receive() const
{
    char buf[1024];
    int serverSockAddrSize =sizeof(serverSockAddr);
    recvfrom(serverSocket, buf, sizeof(buf), 0,(SOCKADDR *)&serverSockAddr, &serverSockAddrSize);
    cout << buf << endl;
}
 
UDPServer::~UDPServer()
{
    closesocket(serverSocket);
    WSACleanup();
    cout << "Server Socketreleased" << endl;
}


 
Client端类定义:
#include
#pragmacomment(lib, "ws2_32.lib")
 
class UDPClient{
private:
    WSADATA wsaData;
    SOCKET clientSocket;
    sockaddr_in clientSockAddr;
public:
    UDPClient();
    void setSockAddr(const char *destAddr,const int destPort);
    void sendData(const char *buf, const intlen) const;
    ~UDPClient();
};


 
Client端实现:
#include"udpClient.h"
#include
 
using namespacestd;
 
UDPClient::UDPClient()
{
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    clientSocket = socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP);
    cout << "Client Socketinitialized" << endl;
}
 
UDPClient::~UDPClient()
{
    closesocket(clientSocket);
    WSACleanup();
    cout << "Client Socketreleased" << endl;
}
 
voidUDPClient::setSockAddr(const char *destAddr, const int destPort)
{
    clientSockAddr.sin_family = AF_INET;
    clientSockAddr.sin_port = htons(destPort);
    clientSockAddr.sin_addr.s_addr =inet_addr(destAddr);
}
 
voidUDPClient::sendData(const char *buf, const int len) const
{
    sendto(clientSocket, buf, len, 0, (SOCKADDR*)&clientSockAddr, sizeof(clientSockAddr));
}


 
Server端调用:
UDPServer* server =new UDPServer;
server->listen(4000);
for (int i = 0; i< 20; i++)
{
    server->receive();
}
delete server;


 
Client端调用:
const char*destAddr = "XXX.XXX.XXX.XXX";
const int destPort= 4000;
const charbuf[1024] = "This is a udp test message";
   
UDPClient* client =new UDPClient;
client->setSockAddr(destAddr,destPort);
for (int i = 0; i< 10; i++)
{
    client->sendData(buf, sizeof(buf));
}
 
delete client;


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