我绑定了一个udp套接字,我正在尝试为特定地址编写一个udp数据报,所以这是我的代码:
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-&gt; writeDatagram之后,它输入if如果它已经失败,但实际上写入了字节(我接收),并发出字节写入的信号。那么为什么要输入if子句?
ps(我测试了ip dest为127.0.0.1)和socket-&gt; errorString()打印“未知错误”
答案 0 :(得分:0)
QAbstractSocket :: waitForBytesWritten()用于调用write()后的TCP套接字。
使用QUdpSocket,API是writeDatagram(),它立即发送(至少在Qt级别,OS我有一个缓冲区)。为了证明这一点,请参阅src / network / socket / qudpsocket.cpp中的writeDatagram()的实现,它发出bytesWritten(已发送);
因此在writeDatagram()之后调用waitForBytesWritten()没有意义。