因此,我试图用TCP服务器创建Winsock UDP服务器,但似乎无法正常工作。正式的winsock文档似乎并未涵盖UDP服务器(据我所知)。
运行中的TCP服务器在这里:
#include <iostream>
#include <ws2tcpip.h>
#include <windows.h>
using namespace std;
int main()
{
const char* port = "888";
char message[50] = {0};
// Initialize WINSOCK
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
// Create the listening socket
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKET DataSocket;
// Initialize the sample struct and get another filled struct of the same type and old values
addrinfo hints, *result(0); ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(0, port, &hints, &result);
// Bind the socket to the ip and port provided by the getaddrinfo and set the listen socket's type to listen
bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
listen(ListenSocket, SOMAXCONN); // Only sets the type to listen ( doesn't actually listen )
// Free unused memory
freeaddrinfo(result);
// Accept a connection
DataSocket = accept(ListenSocket, 0, 0);
cout << "Connected!" << endl << endl;
// Recieve data
while(true){
recv(DataSocket, message, 10, 0);
cout << "Recieved: \n\t" << message << endl << endl;
system("cls");
Sleep(10);
}
// Shutdown
shutdown(DataSocket, SD_BOTH);
shutdown(ListenSocket, SD_BOTH);
WSACleanup();
exit(0);
return 0;
}
如何将其转换为可用的UDP服务器?
以我的经验,仅更改协议和socktype并不能解决问题。
代码更新:
const char* port = "888";
char message[50] = {0};
// Initialize WINSOCK
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
// Create the listening socket
SOCKET DataSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// Initialize the sample struct and get another filled struct of the same type and old values
addrinfo hints, *result(0); ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(0, port, &hints, &result);
// Bind the socket to the ip and port provided by the getaddrinfo and set the listen socket's type to listen
bind(DataSocket, result->ai_addr, (int)result->ai_addrlen);
listen(DataSocket, SOMAXCONN); // Only sets the type to listen ( doesn't actually listen )
// Free unused memory
freeaddrinfo(result);
// Recieve data
while(true){
int bytes = recvfrom(DataSocket, message, 20, 0, 0, 0);
}
最佳答案
要将TCP服务器转换为UDP服务器,至少必须进行以下更改:
将SOCK_STREAM
替换为SOCK_DGRAM
; IPPROTO_TCP
和IPPROTO_UDP
。
删除listen
和accept
呼叫。
将recv
替换为recvfrom
。
将send
替换为sendto
。
关于c++ - 将TCP服务器转换为UDP服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53088219/