我已经绑定了一个 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->writeDatagram 之后,它进入下面的 if 就好像它失败了,但实际上字节被写入(然后我接收)并发出 byteswritten 信号。那么为什么要进入 if 子句呢?
ps(我将 ip dest 测试为 127.0.0.1)并且 socket->errorString() 打印“未知错误”