Итак, я пытаюсь создать UDP-сервер Winsock из TCP-сервера, но я просто не могу заставить его работать. Официальная документация по 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);
}