在iPhone中使用sendto() - 内存分配问题

时间:2012-02-26 08:18:27

标签: iphone

我使用lib发送RTP数据包。在会话建立之后,在质量差的网络上,我收到了大多数数据包的错误,这是发送:

2012-02-26 05:15:53.947[492:7c3b] iovlen size:12 
2012-02-26 05:15:53.950[492:7c3b] iovlen size:160 
2012-02-26 05:15:53.955[492:7c3b] Error sending rtp packet: Cannot allocate memory ; socket=26

可能在gprs上使用iPhone的套接字有一些特定的问题吗? 在下面的代码中,我产生了这个错误:

static int rtp_sendmsg(int sock,mblk_t *m, struct sockaddr *rem_addr, int addr_len){
    int error;
    struct msghdr msg;
    struct iovec iov[MAX_IOV];
    int iovlen;
    for(iovlen=0; iovlen<MAX_IOV && m!=NULL; m=m->b_cont,iovlen++){
        iov[iovlen].iov_base=m->b_rptr;
        iov[iovlen].iov_len=m->b_wptr-m->b_rptr;
        //ortp_warning ("iovlen size:%d",m->b_wptr-m->b_rptr);
    }
    if (iovlen==MAX_IOV){
        ortp_error("Too long msgb, didn't fit into iov, end discarded.");
    }
    msg.msg_name=(void*)rem_addr;
    msg.msg_namelen=addr_len;
    msg.msg_iov=&iov[0];
    msg.msg_iovlen=iovlen;
    msg.msg_control=NULL;
    msg.msg_controllen=0;
    msg.msg_flags=0;
    error=sendmsg(sock,&msg,0);
    return error;
}

任何人都可以建议重构这段代码(我在C中不是很强大,所以代码的最终安静得到了赞赏),这个函数是从这部分代码中调用的:

int
rtp_session_rtp_send (RtpSession * session, mblk_t * m)
{
    int error;
    int i;
    rtp_header_t *hdr;
    struct sockaddr *destaddr=(struct sockaddr*)&session->rtp.rem_addr;
    socklen_t destlen=session->rtp.rem_addrlen;
    ortp_socket_t sockfd=session->rtp.socket;

    hdr = (rtp_header_t *) m->b_rptr;
    /* perform host to network conversions */
    hdr->ssrc = htonl (hdr->ssrc);
    hdr->timestamp = htonl (hdr->timestamp);
    hdr->seq_number = htons (hdr->seq_number);
    for (i = 0; i < hdr->cc; i++)
        hdr->csrc[i] = htonl (hdr->csrc[i]);

    if (session->flags & RTP_SOCKET_CONNECTED) {
        destaddr=NULL;
        destlen=0;
    }

    if (rtp_session_using_transport(session, rtp)){
        error = (session->rtp.tr->t_sendto) (session->rtp.tr,m,0,destaddr,destlen);
        //ortp_warning ("rtp_session_using_transport passed");
    }else{
        //ortp_warning ("rtp_session_using_transport NOT passed");

#ifdef USE_SENDMSG
        error=rtp_sendmsg(sockfd,m,destaddr,destlen);
#else
        if (m->b_cont!=NULL)
            msgpullup(m,-1);
        error = sendto (sockfd, (char*)m->b_rptr, (int) (m->b_wptr - m->b_rptr),
             0,destaddr,destlen);
#endif
    }
    if (error < 0){
        if (session->on_network_error.count>0){
            rtp_signal_table_emit3(&session->on_network_error,(long)"Error sending RTP packet",INT_TO_POINTER(getSocketErrorCode()));
        }else ortp_warning ("Error sending rtp packet: %s ; socket=%i", getSocketError(), sockfd);
        session->rtp.send_errno=getSocketErrorCode();
    }else{
        update_sent_bytes(session,error);
    }
    freemsg (m);
    return error;
}

1 个答案:

答案 0 :(得分:0)

当在狡猾的网络上使用iOS上的sendto()时,

Cannot allocate memory会发生很多。我看到它加载了。基本上,除了优雅地失败之外,你可以做很多事情,并且可能在这个问题发生期间减少通过。这是因为缓冲区正在填满网卡。

关于重构 - 也许在code review.

上发布