PDA

View Full Version : QUdp and waitForReadyRead



babu198649
21st December 2008, 09:52
hi
Using connectToHost() with QUdp socket works fine for writing data with write() function.The code below works fine.

QUdpSocket socket;
socket.connectToHost(QHostAddress::LocalHost,9930) ;
int i=5;
socket.write((char*)&i,sizeof(int));

But using connectToHost() for reading does not work.The below code doesnot work.

QUdpSocket socket;
socket.connectToHost(QHostAddress::LocalHost,9930) ;
if(socket.waitForReadyRead(2000)) //never enters inside this if
qDebug()<<QString(socket.readAll());

wysota
21st December 2008, 10:02
First of all readyRead is emitted when something is to be read from the socket, not when a connection is established. Second of all UDP is a connectionless protocol - there is no point-to-point connection between the hosts. With UDP you can "connect" to a host to mark a default destination for datagrams to be sent, nothing more, not data gets sent there.

babu198649
21st December 2008, 10:13
I am sure that data is received at the port(9930) to which i am connecting(verified with other program).
From Qt docs

if you want to use the standard QIODevice functions read(), readLine(), write(), etc., you must first connect the socket directly to a peer by calling connectToHost().

wysota
21st December 2008, 22:14
Yes, that's correct. But you don't have to use read() or write() with a UDP socket, which doesn't make much sense anyway as you get a "stream" of data in a datagram oriented flow. With QUdpSocket you usually use QUdpSocket::readDatagram() and QUdpSocket::writeDatagram(). As I said connect only marks a default source/destination for data (you can't set a remote host with read() or write() hence they have to use the "default" which is set using connect).

babu198649
22nd December 2008, 12:03
Thank you
I have an application which uses TCP ,I want to test the same application with UDP.So i thought that if i use the connectToHost() function ,then only the QTcp socket type has to be changed to QUdp socket type(all the rest of the code remains same).

wysota
22nd December 2008, 18:49
No, TCP and UDP protocols have nothing in common apart the fact they both concern the transport layer of the OSI model.