因此,我试图从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服务器?根据我的经验,仅仅改变协议和套接字并不能改变它。
代码更新:
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);
}发布于 2018-10-31 16:45:53
若要将TCP服务器转换为UDP服务器,至少必须执行以下更改:
SOCK_STREAM替换为SOCK_DGRAM;IPPROTO_TCP替换为IPPROTO_UDP。listen和accept调用。recv替换为recvfrom。send替换为sendto。https://stackoverflow.com/questions/53088219
复制相似问题