当前位置 : 主页 > 网络编程 > PHP >

用C++创建一个简单的UDP服务端

来源:互联网 收集:自由互联 发布时间:2023-10-08
#include WinSock2.h #include Windows.h #include iostream #pragma comment(lib,"ws2_32.lib") using namespace std ; int main () { WSADATA d ; WORD w = MAKEWORD ( 2 , 0 ); WSAStartup ( w , d ); SOCKET s = socket ( AF_INET , SOCK_DGRAM , 0 ); so


#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main()
{
WSADATA d;
WORD w = MAKEWORD(2, 0);
WSAStartup(w, &d);
SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);

sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = INADDR_ANY;
addr.sin_port = htons(9999);

bind(s, (sockaddr*)&addr, sizeof(addr));

char buf[512] = {0};

sockaddr_in addrClient = {};
int sockLen = sizeof(sockaddr_in);

char bufsend[] = "Hello,UDP Client!";


cout << "UDP SERVER IS START AND BIND TO 9999" << endl;
while (true) {

sendto(s, bufsend, strlen(bufsend), 0, (sockaddr*)&addrClient, sockLen);

int recvLen = recvfrom(s, buf, 512, 0, (sockaddr*)&addrClient, &sockLen);
if (recvLen > 0) {
cout << buf << endl;
}


}

closesocket(s);
WSACleanup();
return 0;
}
上一篇:C++整形转换字符数组跨平台写法
下一篇:没有了
网友评论