发送和发送的任务之一接收UDP帧到自己

时间:2017-01-22 00:07:26

标签: c++ linux sockets udp

我写了一个应用程序,它意味着将UDP数据包发送给自己。 我产生了单独的线程,一个处理事物的Tx端,另一个处理Rx端。但是,似乎Tx帧正在传输帧,但我看不到我的recvfrom()被解除阻塞以接收ta数据。有什么基本的我缺少,这应该是可能的,对吗?
每1秒重复调用一次Tx方法,并在Tx线程变为活动之前启动Rx线程 我可以提供的一些代码是我如何打开我的Tx和Rx插座:
的Tx

int network::sendUDP(BfdDat* pDat)
{
    const char* hostname=0; /* localhost */
    const char* portname="daytime";
    struct addrinfo hints;
    memset(&hints,0,sizeof(hints));
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype=SOCK_DGRAM;
    hints.ai_protocol=0;
    hints.ai_flags=AI_ADDRCONFIG;
    struct addrinfo* res=0;
    if (fd == 0) {
        int err=getaddrinfo(hostname,portname,&hints,&res);
        if (err!=0) {
            cout << "ERROR: sendUDP() getaddrinfo(): " << err < endl;
            exit(err);
        }
        fd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);
        if (fd==-1) {
            cout << "ERROR: sendUDP() socket(): " << errno < endl;
            exit(errno);
        }
    }
    if (sendto(fd,pDat,sizeof(BfdDat),0,
    res->ai_addr,res->ai_addrlen)==-1) {
    exit(errno);
    }

    return 0;

}

的Rx

void network::RxDatTh(void)
{
    cout << "In Rx Thread" << endl;
    BfdDat UDPData;
    struct sockaddr_storage src_addr;
    socklen_t src_addr_len;
    const char* hostname=0; /* wildcard */
    const char* portname="daytime";
    struct addrinfo hints;
    memset(&hints,0,sizeof(hints));
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype=SOCK_DGRAM;
    hints.ai_protocol=0;
    hints.ai_flags=AI_PASSIVE|AI_ADDRCONFIG;
    struct addrinfo* res=0;
    int err=getaddrinfo(hostname,portname,&hints,&res);
    if (err!=0) {
        cout << "ERROR In Rx Thread: after getaddrinfo()" << endl;
        exit(err);
    }

    int fd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);
    if (fd==-1) {
        cout << "ERROR In Rx Thread: after socket()" << endl;
        exit(errno);
    }
    if (bind(fd,res->ai_addr,res->ai_addrlen)==-1) {
        cout << "ERROR In Rx Thread: after bind():" << errno << endl;
        exit(errno);
    }

    freeaddrinfo(res);
    cout << "In Rx Thread: after freeaddrinfo()" << endl;



    src_addr_len=sizeof(src_addr);
    while (true) {
        cout << "waiting for Data..." << endl;
        ssize_t count=recvfrom(fd,&UDPData,sizeof(BfdDat),0,(struct sockaddr*)&src_addr,&src_addr_len);
        if (count==-1) {
            exit(errno);
        } else if (count==sizeof(BfdDat)) {
            warn("datagram too large for UDPData: truncated");
        } else {
            cout << "succesfully received UDPData" << endl;
        }     
    }
}

请注意,这两个方法在不同的线程范围内执行。

0 个答案:

没有答案