I have bound a udp socket and i am trying to write a udp datagram for a specific adress so here is my code:
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;
}
The variable dest is QString, but after i call socket->writeDatagram it enters the if below as if it had fail, but actually the bytes are written (i receive then) and the byteswritten signal is emitted. So why it is entering the if clause?
ps(i tested the ip dest as 127.0.0.1) and the socket->errorString() prints "Unknown error"