Quote Originally Posted by ChrisW67 View Post
Your code extracts do not call bind(): you will not receive if you do not call bind.

I added bind(), but still it returns false! I can only bind my own ip address and not the other machines.

What "result" is -1?

writeDatagram() expects either a QByteArray, address, and port OR a char* buffer, size, address, and port. Which do you think you are doing? Are you ignoring a compiler warning?

no I am not missing any compiler warning. I write char* buffer as the first buffer to writeDatagram(), write is successful, the other machine receives packets successfully.


Your code starting at line 13 says, "While I have no pending datagrams try to read a datagram." Does that sound right to you?
Yes, you are right, I shall omit ! sign.

Here is my final code but still I bind returns false and I cannot receive any packets! (my ip is 100.147 and the machine I am connecting is 100.143)

Qt Code:
  1. #include "UDP.h"
  2.  
  3. UDP::UDP(QObject *parent) :
  4. QObject(parent)
  5. {
  6.  
  7. }
  8. //=======================================
  9. void UDP::UDPInit(int port)
  10. {
  11. socketPort = port;
  12. host = new QHostAddress("192.168.100.143");
  13. myPort = 11000;
  14. udpsocket = new QUdpSocket(this);
  15.  
  16. bool res = udpsocket->bind(QHostAddress("192.168.100.143"),myPort);
  17. connect(udpsocket,SIGNAL(connected()),this,SLOT(socketConnected()));
  18. connect(udpsocket, SIGNAL(readyRead()), this, SLOT(readSocket()));
  19. }
  20. //=======================================
  21. void UDP::socketError( QAbstractSocket::SocketError )
  22. {
  23. qDebug() << "UDPCLIENT ERROR: "<< udpsocket->errorString();
  24. }
  25.  
  26. //========================================
  27. void UDP::socketConnected()
  28. {
  29. qDebug() << "UDPCLIENT : Socket connected!";
  30. emit clientLogMessage(QString("UDPCLIENT : Connected !"));
  31. }
  32.  
  33.  
  34. void UDP::sendCommand(QByteArray data)
  35. {
  36. if(udpsocket->writeDatagram(data.data(),QHostAddress(ip),socketPort)==-1)
  37. emit clientLogMessage(QString("UDPCLIENT : Write problem !"));
  38. else
  39. udpsocket->flush();
  40. }
  41.  
  42. void UDP::readSocket()
  43. {
  44. while (udpsocket->hasPendingDatagrams())
  45. {
  46. QByteArray datagram;
  47. datagram.resize(udpsocket->pendingDatagramSize());
  48. qDebug() << udpsocket->pendingDatagramSize();
  49. udpsocket->readDatagram(datagram.data(), datagram.size(), host, &myPort);
  50. emit dataReceived(datagram);
  51.  
  52.  
  53. qDebug() << datagram.toHex();
  54. }
  55. }
To copy to clipboard, switch view to plain text mode