tcpserver.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "tcpserver.h"
  2. TcpServer::TcpServer(QObject *parent) : QObject(parent)
  3. {
  4. svr = new QTcpServer(this);
  5. connect(svr, SIGNAL(newConnection()), this, SLOT(new_incomming()));
  6. }
  7. void TcpServer::start()
  8. {
  9. if(!svr->listen(QHostAddress::Any,15224)){
  10. printf("15224 listen failed\n");
  11. exit(-1);
  12. }
  13. printf("15224 listen success\n");
  14. }
  15. void TcpServer::new_incomming()
  16. {
  17. so = svr->nextPendingConnection();
  18. connect(so,SIGNAL(readyRead()),this,SLOT(read_data()));
  19. }
  20. void TcpServer::read_data()
  21. {
  22. QString str = QString::fromUtf8(so->readAll());
  23. int begin = str.indexOf("{",0);
  24. int len = str.length();
  25. QString data = str.mid(begin,len-begin+1);
  26. QByteArray ba = data.toLocal8Bit();
  27. ba = QString::fromLocal8Bit(ba).toUtf8();
  28. emit tcp_log(QString("[%1] lighting tcp %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")).arg(data));
  29. QJsonParseError json_error;
  30. QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&json_error);
  31. printf("tcpServer parseErr.error %d\n",json_error.error);
  32. if(json_error.error==QJsonParseError::NoError){
  33. QJsonObject root = jsonDoc.object();
  34. QJsonValue param_val = root.value("params");
  35. QJsonObject param_obj = param_val.toObject();
  36. QString deviceId = param_obj.value("device_id").toString();
  37. int switchStatus = param_obj.value("switch_status").toInt();
  38. emit control_data(deviceId,switchStatus);
  39. }
  40. }
  41. void TcpServer::response_msg(QString msg)
  42. {
  43. QString msgrec = QString("HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: text/plain\r\n\r\n%1").arg(msg);
  44. so->write(msgrec.toUtf8());
  45. so->close();
  46. }