简体   繁体   English

无法使用UDP套接字c ++进行侦听

[英]Unable to listen with UDP socket c++

I am trying to implement a UDP socket for a server c++ file. 我正在尝试为服务器c ++文件实现UDP套接字。 I have the following code to set up the socket 我有以下代码来设置套接字

//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;

When running this code, I get up to the last if statement and a SOCKET_ERROR occurs which throws "couldn't set up listen on socket". 运行此代码时,我会到达最后一个if语句并发生一个SOCKET_ERROR,它会抛出“无法设置侦听套接字”。 When I have this as a TCP connection (as seen below) everything sets up properly: 当我将其作为TCP连接时(如下所示),所有设置都正确:

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

Changing the SOCK_STREAM to SOCK_DGRAM gives me this error. 将SOCK_STREAM更改为SOCK_DGRAM会给我这个错误。 Does anyone know what could be the issue here? 有谁知道这里可能出现什么问题?

You can't listen on a UDP socket. 您无法侦听UDP套接字。 See the documentation: 查看文档:

The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET. sockfd参数是一个文件描述符,它引用SOCK_STREAM或SOCK_SEQPACKET类型的套接字。

As others have stated, you don't use listen() (or accept() ) with UDP. 正如其他人所说,你不使用UDP listen() (或accept() )。 After calling bind() , simply start calling recvfrom() to receive UDP packets. 调用bind() ,只需启动调用recvfrom()即可接收UDP数据包。

if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) is correct for setting up a UDP Socket if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)对于设置UDP套接字是正确的

For receiving data with a UDP socket, you need to use recvfrom() 要使用UDP套接字接收数据,您需要使用recvfrom()

Example: 例:

// 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) {..}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM