QUdpSocket相关 (1)

随手试了下C++ GUI Programming with Qt4 UdpSocket中的例子。

QUdpSocket相关 (1)_第1张图片


void testDialog::sendDatagram()
{
    ss1 = lineEdit1->text();
    ss2 = lineEdit2->text();
    ints = lineEdit3->text().toInt();


    QByteArray datagram;
    QDataStream out(&datagram,QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_7);
    out<<ss1<<ss2<<ints;
    udpsocket.writeDatagram(datagram,QHostAddress::LocalHost,6000);

}


函数解释:pendingDatagramSize  当有数据包读入时返回true.resize 为datageam设置大小pendingDatagramSize 返回udosocket第一个数据包的大小


.....................................   
connect(&udpsocket,SIGNAL(readyRead()),this,SLOT(recvDatagram()));
    udpsocket.bind(QHostAddress::LocalHost,6000);
}


void testDialog::recvDatagram()
{
    QByteArray datagram;
    do{
        datagram.resize(udpsocket.pendingDatagramSize());
        udpsocket.readDatagram(datagram.data(),datagram.size());
    }while(udpsocket.hasPendingDatagrams());

    QDataStream in(&datagram,QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_4_7);
    in>>ss1S>>ss2S>>intsS;
    label->setText(ss1S+ss2S+QString::number(intsS));
}

1, resize 把datageam大小设置为pendingDatagramSize()返回udosocket第一个数据包的大小。


2, readDatagram()

qint64 QUdpSocket::readDatagram ( char * data, qint64 maxSize, QHostAddress * address = 0, quint16 * port = 0 )

Receives a datagram no larger than maxSize bytes and stores it in data. The sender's host address and port is stored in *address and *port (unless the pointers are 0).Returns the size of the datagram on success; otherwise returns -1.

接受不超过maxSize大小的数据包,并吧它存储在data中。

3, char * QByteArray::data ()
Returns a pointer to the data stored in the byte array. The pointer can be used to access and modify the bytes that compose the array. The data is '\0'-terminated, i.e. the number of bytes in the returned character string is size() + 1 for the '\0' terminator.

返回存储在字节数组中数据的指针。


4, int QByteArray::size () const

Returns the number of bytes in this byte array.
返回一个字节数组的字节元素数量,从零开始。
The last byte in the byte array is at position size() - 1. In addition, QByteArray ensures that the byte at position size() is always '\0', so that you can use the return value of data() and constData() as arguments to functions that expect '\0'-terminated strings.

Example:

 QByteArray ba("Hello");
 int n = ba.size();          // n == 5
 ba.data()[0];               // returns 'H'
 ba.data()[4];               // returns 'o'
 ba.data()[5];               // returns '\0'

5, bool QUdpSocket::hasPendingDatagrams () const
Returns true if at least one datagram is waiting to be read; otherwise returns false.

返回true,当至少有一个数据报等待读取的情况下。否则返回false.


6,  qint64 QUdpSocket::pendingDatagramSize () const
Returns the size of the first pending UDP datagram. If there is no datagram available, this function returns -1.
C++ GUi with Qt4书中说,在readyRead信号发送前,发送端可能已经接收了部分数据报。但应为书中的例子是气象气球,书中说因为以前的数据都是过去的天气,已经过时了,所以不需要处理了。作者真会选择例子。。。= =#

你可能感兴趣的:(存储,qt,character,byte,Signal,Pointers)