server doesn't read data from client using QTcpsocket
-
hi everyone
i want to design a mullti thread chat server and client.
first thing that i want to do is to send username to the server and server save it beside socketDescriptor so when i want to find clients sockets i can do it with their usenames
but the problem is that server cant read username.
i have a button that when i press it i want username to be send and socket to connect.
(consider that i use datastream because i migh want to send images too)here is my code in client side:
void MainWindow::on_pushButton_clicked()
{username = ui->lineEdit_2->text(); ui->lineEdit_2->clear(); QByteArray block; QDataStream out(&block,QIODevice::WriteOnly); out<<quint16(0); out<<username; out.device()->seek(0); out<<quint16(block.size() - (int)sizeof(quint16)); socket->write(block); socket->connectToHost(QHostAddress::LocalHost,6400); ui->stackedWidget->setCurrentIndex(0);
}
and my server code to read it is:
void MyServer::incomingConnection(qintptr socketDescriptor)
{
qDebug() << socketDescriptor << " Connecting...";/*begin:here we have to get username*/ /*note that client have to send username as soon as its connected*/ int blockSize; QTcpSocket client; client.setSocketDescriptor(socketDescriptor); QDataStream in(&client); QString username; in >> blockSize; while(true) { if(client.bytesAvailable() == blockSize) { in >> username; qDebug() <<"\nuser " <<username <<"has joined chat\n\n"; break; } } users->insert(username,socketDescriptor); /*end*/ // Every new connection will be run in a newly created thread ThreadClient *thread = new ThreadClient(socketDescriptor, this); // connect signal/slot // once a thread is not needed, it will be beleted later connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start();
}
tnx
-
@Noshad said:
socket->write(block);
socket->connectToHost(QHostAddress::LocalHost,6400);
Hi and welcome to devnet,
you're sending data before connect to the server.
I suggest to check the return value of each socket operation to verify the success; also many Q*Socket methods are asynchronous (the returns immediately without waiting for the operation completion).