Fix problem with QTCPSocket?
-
Hello,
I am having a bit of problem in creating a TCP client/server.
The first message it sends, when the new connection is first established, arrives correctly to the client. However all the messages that I would like to send after are not read correctly (I think that the sending code).
I followed the fortune examples, but I could not get it to work.
Here's come of my code:@// server sending code
void MainWindow::sendMessage()
{
// what is the next pending connection, that is the socket we want to talk to
ui->textBrowser->append("Sending message...");if (!ui->messageInput->text().isEmpty()) { // there is message in the input line messageToSend = ui->messageInput->text(); } else { // otherwise use the predefined message messageToSend = "Predefined message"; } QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << (quint16)0; out << messageToSend; out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); clientConnection->write(block); // send the block of data ui->textBrowser->append("Sent: " + messageToSend);
}
@@// client receiving code
QDataStream in(newSocket); in.setVersion(QDataStream::Qt_4_0); if (blockSize == 0) { qDebug() << "1"; if (newSocket->bytesAvailable() < (int)sizeof(quint16)) return; in >> blockSize; qDebug() << blockSize << " " << newSocket->bytesAvailable(); } if (newSocket->bytesAvailable() < blockSize) { qDebug() << "2"; return; } QString nextMessage; in >> nextMessage; qDebug() << nextMessage;
@
nextMessage should be the message that was sent by the server.
I think that the client is not reading correctly.Can anyone help me out?
Thanks -
Ah, sorry for repost.
Just assume that the connection between client and server is successful.
I am using something like this:In client:
@
connect(newSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
@In server:
@
connect(newServer, SIGNAL(newConnection()), this, SLOT(sendMessage()));
@ -
newConnection() "triggers" only when there are new sockets who want to connect to the sever. apparently, it is already connected so newConnection() will not be called again.
If I remember clearly, that example follows these steps:
client connects
server accepts
server sends message
...and server disconnects client (or client disconnects itself?)
..then return to step 1.
Try disconnecting the client t the end of "sendMessage()" function.
If your goal is to have the server only to send messages, this is OK. But if your goal is a "bidirectional" server-client connection, I don't recommend it.
-
But my thing is that I want to keep the connection open, I don't want to close it every time a message it's sent.
Is it possible to do that? -
[quote author="QTDavid" date="1358337004"]But my thing is that I want to keep the connection open, I don't want to close it every time a message it's sent.
Is it possible to do that?[/quote]Yes, it is possible. Might be better if you have the code to revise.