【问题标题】:Unable to listen with UDP socket c++无法使用 UDP 套接字 C++ 监听
【发布时间】: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 套接字上的连接请求,因为它是无连接

标签: c++ sockets udp


【解决方案1】:

您不能在 UDP 套接字上侦听。请参阅文档:

sockfd 参数是一个文件描述符,它引用 SOCK_STREAM 或 SOCK_SEQPACKET 类型的套接字。

【讨论】:

    【解决方案2】:

    正如其他人所说,您不要将listen()(或accept())与UDP 一起使用。调用bind()后,直接调用recvfrom()接收UDP包即可。

    【讨论】:

      【解决方案3】:

      if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) 正确设置 UDP Socket

      使用UDP套接字接收数据,需要使用recvfrom()

      例子:

      // setup 
      char RecvBuf[1024];
      int BufLen = 1024;
      sockaddr_in SenderAddr;
      int SenderAddrSize = sizeof (SenderAddr);
      // ........ 
      if (recvfrom(s, RecvBuf, BufLen, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize) == SOCKET_ERROR) {..}
      

      【讨论】:

      • 不是这样的。您需要将recvfrom() 的结果存储在一个变量中,以便获得数据长度。
      • 我举了一个例子,说明如何使用 UDP 套接字接收,它可以工作。他没有要求数据长度。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 2011-02-15
      • 2015-05-26
      • 2017-09-04
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多