class Dialog : public QDialog{ Q_OBJECTpublic: explicit Dialog(QWidget *parent = 0); ~Dialog();private: QTcpServer *server; QTcpSocket *serverSocket; Ui::Dialog *ui;private slots: void on_serverConnect(); void on_dataRead();};Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog){ ui->setupUi(this); server = new QTcpServer(this); connect(server, SIGNAL(newConnection()), this, SLOT(on_serverConnect())); server->listen(QHostAddress::Any, 3355);}void Dialog::on_serverConnect(){ serverSocket = server->nextPendingConnection(); connect(serverSocket, SIGNAL(readyRead()), this, SLOT(on_dataRead())); QTextCursor curs = ui->textEdit->textCursor(); curs.movePosition(QTextCursor::End); curs.insertText("Connected!\r\n");}void Dialog::on_dataRead(){ QByteArray readingData; while(serverSocket->isReadable()) readingData.append(serverSocket->readAll()); QTextCursor curs = ui->textEdit->textCursor(); curs.movePosition(QTextCursor::End); curs.insertText(readingData);}
CServerConnection::CServerConnection(QObject *parent) : QObject(parent){ connection = new QTcpSocket(this); connection->connectToHost("localhost", 3355, QIODevice::ReadWrite); connection->waitForConnected();}void CServerConnection::SendData(QByteArray data){ if (!connection->isOpen()) return; connection->write(QByteArray("Test String")); connection->flush();}
C++ (Qt)void Dialog::on_dataRead(){ while(serverSocket->isReadable()) readingData.append(serverSocket->readAll());}
void Dialog::on_dataRead(){ struct { int CMD; int X; int Y; int Z; int Power; } sendingStruct; QByteArray readingData; while(serverSocket->bytesAvailable() > 0) readingData.append(serverSocket->readAll()); memcpy(&sendingStruct, readingData.data() +1, sizeof(sendingStruct)); QTextCursor curs = ui->textEdit->textCursor(); curs.movePosition(QTextCursor::End); QString text = QString("CMD= %1\r\nX= %2\r\nY= %3\r\nZ= %4\r\nPower= %5").arg(sendingStruct.CMD). arg(sendingStruct.X).arg(sendingStruct.Y).arg(sendingStruct.Z).arg(sendingStruct.Power); curs.insertText(text);}
void CServerConnection::SendData(QMap<QString, int> data){ if (!connection->isOpen()) return; struct { int CMD; int X; int Y; int Z; int Power; } sendingStruct; for (int i = 0; i < 100; i++) { sendingStruct.CMD = 33; sendingStruct.X = i; sendingStruct.Y = i+1; sendingStruct.Z = i*2; sendingStruct.Power = i*i; sendData.clear(); char *buf = new char[sizeof(sendingStruct)]; memcpy(buf, &sendingStruct,sizeof(sendingStruct)); sendData.append(STX); // начало пакета sendData.append(buf, sizeof(sendingStruct)); sendData.append(ETX); // конец пакета connection->write(sendData); connection->waitForBytesWritten(); delete[] buf; }}
char *buf = new char [sizeof(sendingStruct) + 2]; while(serverSocket->bytesAvailable() > 0) { serverSocket->read(buf, sizeof(sendingStruct) + 2); memcpy(&sendingStruct, buf +1, sizeof(sendingStruct)); ........ }