visiostudio udp接收数据 C++ 客户端代码
时间: 2024-11-15 12:34:12 浏览: 21
在Visual Studio中创建一个C++客户端,用于通过UDP协议接收数据,你可以按照以下步骤编写代码:
```cpp
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
// UDP服务器地址和端口
const char* serverAddress = "your_server_ip";
const unsigned short serverPort = 12345;
class UdpClient {
public:
UdpClient() {
// 初始化Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize Winsock!" << std::endl;
return;
}
socket_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (socket_ == INVALID_SOCKET) {
std::cerr << "Failed to create socket!" << std::endl;
WSACleanup();
return;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(serverPort);
addr.sin_addr.S_un.S_addr = inet_addr(serverAddress);
// 设置发送和接收缓冲区大小
int opt = 1; // SO_BROADCAST for broadcast packets
setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, (char*)&opt, sizeof(opt));
int bufsize = 1024;
setsockopt(socket_, SOL_SOCKET, SO_RCVBUF, (char*)&bufsize, sizeof(bufsize));
}
~UdpClient() {
closesocket(socket_);
WSACleanup();
}
void startReceiving() {
char buffer[1024];
while (true) {
const int bytes_received = recvfrom(socket_, buffer, sizeof(buffer), 0, &remoteAddr, nullptr);
if (bytes_received > 0) {
std::cout << "Received data from " << inet_ntoa(remoteAddr.sin_addr) << ":" << ntohs(remoteAddr.sin_port)
<< ": " << buffer << std::endl;
} else if (bytes_received == 0) {
std::cout << "Connection closed by the server." << std::endl;
break;
} else {
std::cerr << "Error receiving data: " << WSAGetLastError() << std::endl;
}
}
}
private:
SOCKET socket_;
sockaddr_in addr, remoteAddr;
};
int main() {
UdpClient client;
try {
client.startReceiving();
} catch (std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
阅读全文