Udp 使用示例
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#include<thread>
SOCKET sendSocket;
sockaddr_in localAddr;
sockaddr_in targetAddr;
void initSocket()
{
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
std::cerr << "WSAStartup failed: " << result << std::endl;
return ;
}
// 创建 UDP 套接字
sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sendSocket == INVALID_SOCKET) {
std::cerr << "Error at socket(): " << WSAGetLastError() << std::endl;
WSACleanup();
return ;
}
// (可选)绑定到特定本地端口(例如 12345)
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(12345); //发送使用此端口 接收也是使用此端口
localAddr.sin_addr.s_addr = INADDR_ANY; // 使用任意可用的本地 IP 地址
// 绑定套接字到本地端口
if (bind(sendSocket, (SOCKADDR*)&localAddr, sizeof(localAddr)) == SOCKET_ERROR) {
std::cerr << "Bind failed with error: " << WSAGetLastError() << std::endl;
closesocket(sendSocket);
WSACleanup();
return ;
}
// 目标地址信息
targetAddr.sin_family = AF_INET;
targetAddr.sin_port = htons(8080); // 目标端口
targetAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // 目标 IP 地址
const char* sendData = "Hello, UDP!";
}
void sendThread()
{
while (1)
{
Sleep(1000);
int bytesSent = sendto(sendSocket, "123", 4, 0, (SOCKADDR*)&targetAddr, sizeof(targetAddr));
std::cout << "send" << std::endl;
}
}
void recvThread()
{
while (1)
{
Sleep(100);
unsigned longsocketMode = 1;
ioctlsocket(sendSocket, FIONBIO, &socketMode);
int fromlen = sizeof(localAddr);
char ch[64] = { 0 };
int err = recvfrom(sendSocket, ch, 64, 0, (struct sockaddr *) &localAddr, &fromlen);//block
if (err > 0)
{
std::cout << ch << std::endl;
}
}
}
int main()
{
initSocket();
std::thread th1(&sendThread);
th1.detach();
std::thread th2(&recvThread);
th2.detach();
getchar();
closesocket(sendSocket);
WSACleanup();
return 0;
}
!
原文地址:https://blog.csdn.net/u013174817/article/details/145097365
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!