Pinger.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "Pinger.h"
  2. #include <QUdpSocket>
  3. #include <QTime>
  4. #include <QTimerEvent>
  5. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6. Pinger::Pinger(const QHostAddress &host, quint16 port, QObject *parent) :
  7. QObject(parent),
  8. mySocket(new QUdpSocket(this)),
  9. myHost(host),
  10. myPort(port),
  11. myTimerID(-1)
  12. {
  13. mySocket->connectToHost(host, port);
  14. }
  15. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  16. void Pinger::ping()
  17. {
  18. mySocket->write("\xff\xff\xff\xffk\n");
  19. mySocket->waitForBytesWritten(500);
  20. myTime.start();
  21. myTimerID = startTimer(1000);
  22. connect(mySocket, SIGNAL(readyRead()), SLOT(pong()));
  23. }
  24. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  25. void Pinger::pong()
  26. {
  27. emit finished(myHost, myPort, myTime.elapsed());
  28. disconnect(mySocket, SIGNAL(readyRead()), this, SLOT(pong()));
  29. killTimer(myTimerID);
  30. myTimerID = -1;
  31. }
  32. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  33. void Pinger::timerEvent(QTimerEvent *e)
  34. {
  35. if(e->timerId() != myTimerID)
  36. return;
  37. emit finished(myHost, myPort, myTime.elapsed());
  38. disconnect(mySocket, SIGNAL(readyRead()), this, SLOT(pong()));
  39. killTimer(myTimerID);
  40. myTimerID = -1;
  41. }