#include "tcpserver.h" TcpServer::TcpServer(QObject *parent) : QObject(parent) { svr = new QTcpServer(this); connect(svr, SIGNAL(newConnection()), this, SLOT(new_incomming())); } void TcpServer::start() { if(!svr->listen(QHostAddress::Any,15224)){ printf("15224 listen failed\n"); exit(-1); } printf("15224 listen success\n"); } void TcpServer::new_incomming() { so = svr->nextPendingConnection(); connect(so,SIGNAL(readyRead()),this,SLOT(read_data())); } void TcpServer::read_data() { QString str = QString::fromUtf8(so->readAll()); int begin = str.indexOf("{",0); int len = str.length(); QString data = str.mid(begin,len-begin+1); QByteArray ba = data.toLocal8Bit(); ba = QString::fromLocal8Bit(ba).toUtf8(); emit tcp_log(QString("[%1] lighting tcp %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")).arg(data)); QJsonParseError json_error; QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&json_error); printf("tcpServer parseErr.error %d\n",json_error.error); if(json_error.error==QJsonParseError::NoError){ QJsonObject root = jsonDoc.object(); QJsonValue param_val = root.value("params"); QJsonObject param_obj = param_val.toObject(); QString deviceId = param_obj.value("device_id").toString(); int switchStatus = param_obj.value("switch_status").toInt(); emit control_data(deviceId,switchStatus); } } void TcpServer::response_msg(QString msg) { 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); so->write(msgrec.toUtf8()); so->close(); }