SocketClient.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // Created by Tobias Hieta on 26/08/15.
  3. //
  4. #include <QCoreApplication>
  5. #include <QLocalSocket>
  6. #include <qqueue.h>
  7. #include "LocalJsonClient.h"
  8. class SocketClient : public QObject
  9. {
  10. Q_OBJECT
  11. public:
  12. SocketClient() : QObject(NULL)
  13. {
  14. m_socket = new LocalJsonClient("inputSocket", this);
  15. m_socket->connectToServer();
  16. connect(m_socket, &LocalJsonClient::messageReceived, this, &SocketClient::gotMessage);
  17. }
  18. void sendCommand(const QString& command)
  19. {
  20. m_commands.enqueue(command);
  21. }
  22. Q_SLOT void gotMessage(const QVariantMap& message)
  23. {
  24. qDebug() << message;
  25. doSendCommand();
  26. }
  27. void doSendCommand()
  28. {
  29. while (!m_commands.isEmpty())
  30. {
  31. QString cmd = m_commands.dequeue();
  32. QVariantMap obj;
  33. obj.insert("client", "socket-client");
  34. obj.insert("source", "direct");
  35. obj.insert("keycode", cmd);
  36. m_socket->sendMessage(obj);
  37. qDebug() << "Sending:" << cmd;
  38. }
  39. m_socket->waitForBytesWritten(60 * 1000);
  40. m_socket->close();
  41. exit(EXIT_SUCCESS);
  42. }
  43. private:
  44. LocalJsonClient* m_socket;
  45. QQueue<QString> m_commands;
  46. };
  47. int main(int argc, char** argv)
  48. {
  49. QCoreApplication app(argc, argv);
  50. SocketClient* client = new SocketClient();
  51. for (int i = 1; i < argc; i ++)
  52. client->sendCommand(QString::fromUtf8(argv[i]));
  53. return app.exec();
  54. }
  55. #include "SocketClient.moc"