QT中TCP/UDP通信数据的组织

QT中TCP/UDP通信数据的组织


    //组装数据包
    QString msgType = "MSG_CLIENT_NEW_CONN";
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    QString xxx;
    QString yyy;
    QString zzz;
    out << (quint16)0 << msgType << xxx << yyy << zzz;
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
    udpSocket->writeDatagram(block.data(), block.size(), QHostAddress(ip), (quint16)port);


    //读取数据包
    QByteArray block;
    block.resize(udpSocket->pendingDatagramSize());
    if ( -1 == udpSocket->readDatagram(block.data(), block.size(), &senderIp, &senderPort))
            continue;
    QDataStream in(&block,QIODevice::ReadOnly);
    quint16 dataGramSize;
    QString msgType; 
    in >> dataGramSize >> msgType;
    if ( "MSG_CLIENT_NEW_CONN" == msgType )
    {
       QString xxx;
       QString yyy;
       QString zzz;
       in >> xxx >> yyy >> zzz;

    }

你可能感兴趣的:(qt)