mythread.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // mythread.cpp
  2. #include "mythread.h"
  3. #include "QProcess"
  4. #include "QtGlobal"
  5. #ifdef Q_OS_LINUX
  6. // linux
  7. #define CMD_LEFT "xdotool key Left"
  8. #define CMD_RIGHT "xdotool key Right"
  9. #define CMD_ESC "xdotool key Escape"
  10. #define CMD_F5 "xdotool key F5"
  11. #endif
  12. #ifdef Q_OS_WIN32
  13. // win
  14. #define CMD_LEFT "KeyUtil Left"
  15. #define CMD_RIGHT "KeyUtil Right"
  16. #define CMD_ESC "KeyUtil Esc"
  17. #define CMD_F5 "KeyUtil F5"
  18. #endif
  19. MyThread::MyThread(long ID, QObject *parent) :
  20. QThread(parent)
  21. {
  22. this->socketDescriptor = ID;
  23. }
  24. void MyThread::run()
  25. {
  26. // thread starts here
  27. qDebug() << socketDescriptor << " Starting thread";
  28. socket = new QTcpSocket();
  29. if(!socket->setSocketDescriptor(this->socketDescriptor))
  30. {
  31. emit error(socket->error());
  32. return;
  33. }
  34. connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()),Qt::DirectConnection);
  35. connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()),Qt::DirectConnection);
  36. qDebug() << socketDescriptor << " Client connected";
  37. // make this thread a loop
  38. exec();
  39. }
  40. void MyThread::readyRead()
  41. {
  42. QByteArray Data = socket->readAll();
  43. QString d =QString::fromUtf8(Data);
  44. qDebug() << socketDescriptor << " Data in: " << d;
  45. QProcess p(0);
  46. if(!d.trimmed().compare("Left")){
  47. //receive left
  48. qDebug()<<socketDescriptor<<"deal left";
  49. p.start(CMD_LEFT);
  50. p.waitForFinished();
  51. }else if(!d.trimmed().compare("Right")){
  52. //receive Right
  53. qDebug()<<socketDescriptor<<"deal Right";
  54. p.start(CMD_RIGHT);
  55. p.waitForFinished();
  56. }else if(!d.trimmed().compare("Escape")){
  57. //receive Escape
  58. qDebug()<<socketDescriptor<<"deal Escape";
  59. p.start(CMD_ESC);
  60. p.waitForFinished();
  61. }else if(!d.trimmed().compare("F5")){
  62. //receive F5
  63. qDebug()<<socketDescriptor<<"deal F5";
  64. p.start(CMD_F5);
  65. p.waitForFinished();
  66. }
  67. socket->write(Data);
  68. }
  69. void MyThread::disconnected()
  70. {
  71. qDebug() << socketDescriptor << " Disconnected";
  72. socket->deleteLater();
  73. exit(0);
  74. }