gpt4 book ai didi

c++ - 无法使用 UDP 套接字 c++ 收听

转载 作者:行者123 更新时间:2023-11-30 02:43:02 24 4
gpt4 key购买 nike

我正在尝试为服务器 C++ 文件实现 UDP 套接字。我有以下代码来设置套接字

//Create the server socket
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
throw "can't initialize socket";


//Fill-in Server Port and Address info.
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
sa.sin_addr.s_addr = htonl(INADDR_ANY);


//Bind the server port

if (bind(s, (LPSOCKADDR)&sa, sizeof(sa)) == SOCKET_ERROR)
throw "can't bind the socket";
cout << "Bind was successful" << endl;

//Successfull bind, now listen for client requests.

if (listen(s, 10) == SOCKET_ERROR)
throw "couldn't set up listen on socket";
else cout << "Listen was successful" << endl
<< "Waiting to be contacted for transferring files..." << endl;

运行此代码时,我到达最后一个 if 语句,出现 SOCKET_ERROR,抛出“无法在套接字上设置监听”。当我将其作为 TCP 连接(如下所示)时,一切都设置正确:

 if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
throw "can't initialize socket";

将 SOCK_STREAM 更改为 SOCK_DGRAM 会给我这个错误。有谁知道这里可能是什么问题?

最佳答案

你不能监听 UDP 套接字。请参阅文档:

The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET.

关于c++ - 无法使用 UDP 套接字 c++ 收听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26539470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com