2013-03-14 73 views
0

我已綁定一個UDP套接字,我試圖寫一個特定ADRESS所以這裏一個UDP數據報是我的代碼:QT 5.0 QUdpSocket提供不會觸發waitforbyteswritten

UDP::UDP(QObject *parent) : 
    QObject(parent) 
{ 
    socket = new QUdpSocket(this); 
    QObject::connect(socket,SIGNAL(bytesWritten(qint64)),this,SLOT(bytesWritten(qint64))); 
    QObject::connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead())); 
} 
void UDP::connect(int port){ 

if(socket->state()==QAbstractSocket::BoundState){ 
    qDebug()<<"already bound try to disconnect"; 
    socket->close(); 
} 
    if(socket->bind(QHostAddress::Any,port,QAbstractSocket::ShareAddress|QAbstractSocket::Reuse AddressHint)){ 
     qDebug()<< "listening"; 
     emit changeStatus("UDP: escutando("+QString::number(port)+")"); 
    }else{ 
     qDebug()<< "error no bind"; 
     emit changeStatus("UDP: erro no bind("+QString::number(port)+")"); 
    } 
} 

void UDP::bytesWritten(qint64 bytes){ 
    qDebug()<<"bytes written:"<<bytes; 
    emit changeStatus("UDP: enviado"); 
} 

void UDP::readyRead(){ 
    qDebug()<<"ready to read"; 
    QByteArray datagram; 
    QHostAddress sender; 
    quint16 senderPort; 

    datagram.resize(socket->pendingDatagramSize()); 
    socket->readDatagram(datagram.data(),datagram.size(),&sender,&senderPort); 
    qDebug()<< "datagram received from " << sender.toString(); 

    emit receivedUDPdata(datagram); 

} 
bool UDP::write(QString dest,int port, QString buffer, int size){ 
    char *finalOutput; 
    finalOutput = new char[size]; 
    unsigned int j=0; 

    for(unsigned int i=0;i<size;i++){ 
     if(buffer[i]== '\\'){ 
      switch (buffer.at(++i).toLatin1()){ 
      case 'r': 
       finalOutput[j++] = '\r'; 
       break; 
      case 'n': 
       finalOutput[j++]= '\n'; 
       break; 
      case 't': 
       finalOutput[j++]='\t'; 
       break; 
      case '\\': 
       finalOutput[j++]='\\'; 
       break; 
      } 
     }else{ 
      finalOutput[j++]= buffer[i].toLatin1(); 
     } 
    } 
    socket->writeDatagram(finalOutput,j,QHostAddress(dest),port); 
    if(!socket->waitForBytesWritten(2000)){ 
     qDebug() << "UDP Couldnt write."; 
     emit changeStatus("UDP: Não foi possível escrever"); 
     return false; 
    } 
    return true; 
} 

變量dest爲QString的,但在我調用socket-> writeDatagram它進入如果下面如果它失敗,但實際上字節被寫入(我接收)然後發送字節寫入的信號。那麼爲什麼它要進入if子句呢?

PS(我測試的IP DEST如127.0.0.1)和插座 - > Errorstring,則()打印 「未知錯誤」

+0

你能分享更多的代碼嗎? 'socket-> writeDatagram()'之前有什麼? – dschulz 2013-03-15 00:00:01

+0

當然!已經發布了它 – user1553386 2013-03-15 16:44:43

+0

當你運行你的代碼時,你不會得到以下內容:UnconnectedState中不允許使用QAbstractSocket :: waitForBytesWritten()嗎? – 2013-11-26 23:32:05

回答

0

QAbstractSocket :: waitForBytesWritten()是用於TCP套接字,調用寫入之後()。

對於QUdpSocket,API是writeDatagram(),它立即發送(至少在Qt級別,操作系統有一個緩衝區,我想)。爲了證明這一點,請參閱src/network/socket/qudpsocket.cpp中writeDatagram()的實現,它會發出bytesWritten(已發送);

因此,在writeDatagram()之後調用waitForBytesWritten()沒有意義。