I have a linux machine and a Windows machine I have a C++ program witch acts as a server on the linux machine and a Qt application witch acts as a client on windows machine. I use the socket as a encryption key (basic xor encryption)
The problem is when I hit multiple times connect I get bogus strings. I think the problem is in qt application here is my code. I have tried to put a global flag busy to prevent the user from hitting the connect button manny times but this flag never gets triggered.
Why? Should I use a mutex? If yes how?
void MainWindow::performRead()
{
QTcpSocket * sock = static_cast<QTcpSocket*>(this->sender());
if (key == 0)
{
busy = true;
QString recv(sock->readLine());
key = recv.toInt();
qDebug() << "Cheia este " << key;
char * response = enc_dec("#AUTH|admin|admin",strlen("#AUTH|admin|admin"),key);
sock->write(response);
}
else
{
busy = true;
while (sock->bytesAvailable() > 0)
{
unsigned short word;
sock->read((char*)(&word),2);
qDebug()<<word;
QByteArray bts = sock->read(word);
char * decodat = enc_dec((char*)bts.data(),bts.length() - 2,key);
char testx[2];
sock->peek(&testx[0],2);
qDebug() << decodat;
}
}
busy = false;
}
void MainWindow::on_pushButton_clicked()
{
if (!busy)
{
key = 0;
QTcpSocket * sock = new QTcpSocket();
connect(sock,SIGNAL(readyRead()),this,SLOT(performRead()));
sock->connectToHost("194.110.212.46",6550);
}
else qDebug()<<"Can't you see I am busy??" << endl;
}
char * enc_dec(char * str,int len, int key)
{
unsigned char keys[2];
keys[0] = (unsigned char)key;
keys[1] = keys[0] ^ 255;
char * nou = new char[len + 1];
nou[len] = '\0';
for (int i = 0; i < len; i++)
{
char tmpy = str[i] ^ keys[i % 2];
nou[i] = tmpy;
}
return nou;
}
Your code is pretty messed up, here are my suggestions:
connectthe socket on every button hit – you are overwriting what you had before, and do unnecessary work – TCP connection establishment is expensive,