PDA

View Full Version : QDataSream: No Device



jonging
20th June 2006, 20:13
Hi. I'm writing a few small test socket programs using Qt libraries without using the event loop (i.e. no Signals and Slots). Here is the source code for a small server:

#include <QtNetwork>
#include <iostream>
#include <qdatastream.h>

int main(int *argc, char *argv[]){


QTcpServer server;
QTcpSocket *socket;
server.listen(QHostAddress::LocalHost,8000);
bool timeout;
server.waitForNewConnection(50000,&timeout);
socket=server.nextPendingConnection();
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_0);
int number;
in>>number;
std::cout<<number<<std::endl;
}

and a simple client:

#include <QtNetwork>
#include <iostream>
#include <qdatastream.h>

int main(int *argc, char *argv[]){


QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost,8000) ;
if (!socket.waitForConnected(5000)) {

std::cout<<"Cannot connect to GUI."<<std::endl;
return 0;
}
QDataStream out(&socket);
out.setVersion(QDataStream::Qt_4_0);
out<<1;
}

when I run the server (receiving data) and then the client, the server displays the message "QDataStream: No device" followed by a zero. What am I doing wrong? thanks.

Edit: I forgot to note that the client displays the error message "Cannot connect to GUI"

wysota
20th June 2006, 20:38
QTcpServer needs an event loop running. So does QTcpSocket.

jonging
20th June 2006, 20:57
Actually, the QT documentation site says that both QTcpSocket and QTcpServer can be used without an event loop.

jacek
20th June 2006, 21:27
You must initialize timeout to false (see here (http://www.trolltech.com/developer/task-tracker/index_html?method=entry&id=114872)) and you have to invoke QIODevice::waitForReadyRead() and QIODevice::waitForBytesWritten() in proper places to wait for data to be passed over the network.

jonging
20th June 2006, 21:40
Awesome, thanks a lot. I would never have been able to locate that QT bug. I still have a little trouble with the two other blocking calls because I get a segmentation fault. Do you have any idea what could be causing this?

wysota
20th June 2006, 22:30
Most segfaults are caused by dangling pointers. Use a debugger to see where it crashes and what parameters were passed to functions on the call stack.