PDA

View Full Version : Communication between Client Qt4 and Server in C



hormoz1989
25th March 2011, 18:35
I have my client with Qt4 C++ and my server is in C. I am trying o send a text from server to client and client should print it out, but It does not work. Is there any way to make that happened?

Client:

void Client::readFortune()
{
QDataStream in(tcpSocket);
//in.setVersion(QDataStream::Qt_4_0);
QTextStream out ( stdout) ;
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;

in >> blockSize;

}

if (tcpSocket->bytesAvailable() < blockSize)
return;

QString nextFortune;
in >> nextFortune;

if (nextFortune == currentFortune) {
QTimer::singleShot(0, this, SLOT(requestNewFortune()));
return;
}

currentFortune = nextFortune;
// It should set it here
statusLabel->setText( currentFortune );
getFortuneButton->setEnabled(true);
}


Server:



while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}

inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);

if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
if (send(new_fd, "Hello, world!", 13, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}

wysota
25th March 2011, 20:12
You are sending a plain string but trying to receive it through QDataStream, it has no chance of working. Instead of blindly copying bad examples try to think how your communication should look like.

hormoz1989
25th March 2011, 20:29
Thank you for reply. I understand that. What function I need to use in order to work. Any Help please. Thank you

squidge
25th March 2011, 23:58
Your code doesn't even make sense. It is like you are randomly copy and pasting code and hoping it'll match your requirement. For example, you are sending the standard string "Hello, World!", but then you are retrieving an integer if blockSize == 0, and you are also using incompatible methods.

Stop trying to hack up code, read the docs and start from scratch. Learn how every functions works before trying to use it.