随手试了下C++ GUI Programming with Qt4 UdpSocket中的例子。
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)); }
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'
返回true,当至少有一个数据报等待读取的情况下。否则返回false.