I had a socket connection with UNIX C ++ sockets, where after connecting I had a loop to read a byte by byte until I had a complete message. I know the first two bytes of the message I'm going to receive, and its length (15 bytes). So the function looked like this:
bool mastControl::findPacket(int sockfd, st_messageMastToPc * messageReceived, bool * connected) {
int n = 0;
bool messageFound = false;
char * buffer = (char *) messageReceived;
unsigned int pos = 0;
while ( ((n = read(sockfd, &(buffer[pos]), 1)) > 0) and not messageFound) {
if (n == 1) {
pos++;
if ( (pos == 1) && (buffer[0] == 0x02)) {
std::cout << "INFO - Rcv1" << std::endl;
} else if ( (pos == 2) && (buffer[1] == 0x33) ) {
std::cout << "INFO - Rcv2" << std::endl;
} else if (pos >= uiMessageMastToPcSize) {
messageFound = true;
std::cout << "INFO - Complete message received" << std::endl;
} else if (pos <= 2) {
std::cout << "WARN - Reseting (byte " << pos << " -> " << int(pos) << ")" << std::endl;
pos = 0;
}
}
}
if (n < 0){
*connected = false;
}
return messageFound;
}
Now I am implementing the same with QTcpSockets. The connection is established, and then I call:
if(socket->waitForReadyRead(Global::tiempoMaximoDeEsperaParaRecibirDatosMastil)){
if (findPacket(socket, &messageReceived)) {
qDebug()<<"New packet found!";
}
}
So, I wait until some information is read that I will read, and then call findPacket, which is now almost the same, reading byte by byte:
bool mastControl::findPacket(QTcpSocket *socket, st_messageMastToPc * messageReceived) {
int n = 0;
bool messageFound = false;
char * buffer = (char *) messageReceived;
unsigned int pos = 0;
while ( ((n = socket->read(&(buffer[pos]), 1)) >= 0) and not messageFound) {
if (n == 1) {
qDebug()<<"Recibido: "<<buffer[pos]<<", en pos: "<<pos;
pos++;
if ( (pos == 1) && (buffer[0] == 0x022)) {
qDebug()<<"0x02 in first position";
} else if ( (pos == 2) && (buffer[1] == 0x33) ) {
qDebug()<<"0x33 in second";
std::cout << "INFO - Rcv2" << std::endl;
} else if (pos >= uiMessageMastToPcSize) {
messageFound = true;
std::cout << "INFO - Complete message received" << std::endl;
} else if (pos <= 2) {
std::cout << "WARN - Reseting (byte " << pos << " -> " << int(pos) << ")" << std::endl;
pos = 0;
}
}
}
if (n < 0){
qDebug()<< "Disconnected. Reason: " << socket->errorString();
}
return messageFound;
}
, . waitForReadyRead, findPacket, 4 . . FindPacket , , 0 . . , , , - .
, ? -? , 0 ? ++?