【发布时间】:2014-10-24 09:54:00
【问题描述】:
我正在尝试为服务器 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 会出现此错误。有谁知道这里可能是什么问题?
【问题讨论】:
-
您不能
listen处理 UDP 套接字上的连接请求,因为它是无连接。