QT Socket通信一
- UDP是轻量级的套接字通信,具有广播,组播等功能。UDP通过数据包传输数据,不会又分包和组包的问题,方便快捷。本文介绍QT UDP通信实例。
QUdpSocket类
include
- 要使用QT的QUdpSocket类,需要在pro文件的中添加:
QT += network
- 在.h中添加
#include <QUdpSocket>
#include <QtNetwork>
官方实例
//服务端绑定端口,能够收到固定端口的广播信号。
void Server::initSocket()
{
udpSocket = new QUdpSocket(this); //创建对象
udpSocket->bind(QHostAddress::LocalHost, 7755); //绑定端口
//当UDP收到消息后,会发送readyRead信号,
//连接成功有 connected,断开连接有,disconnected信号。
connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
}
void Server::readPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams()) {
//从缓冲区中读取数据,
QNetworkDatagram datagram = udpSocket->receiveDatagram();
//处理数据。
processTheDatagram(datagram);
}
}
官方实例中
广播和接收自定义结构体/消息体
消息体
添加msg_type.h文件,声明结构体。例如如下
typedef struct
{
unsigned int send_id; // 发送方的ID(网络的IP、SRIO的ID)
unsigned int recv_id; // 接收方的ID(网络的IP、SRIO的ID)
unsigned int msg_type : 8; // 消息类型
unsigned int len : 24; // 消息长度,字节数
unsigned int conn_type: 8; // 连接类型,TCP、UDP等
unsigned int pkg_num : 8; // 总的包数(用于组包传输)
unsigned int pkg_idx : 8; // 子包索引(用于组包传输),从1计数
unsigned int rsvd : 8; // 保留位
unsigned int check_sum; // 校验位
char* load; // 消息体地址
} DispCtrlMsg;
广播
/**
* @brief Widget::on_UDPButton_clicked
* 从6000端口广播消息
*/
void MainWindow::on_udpBroadButton_clicked()
{
quint16 targetPort = ui->lineEdit_udpport->text().toUShort();
DispCtrlMsg *sendMsg = new DispCtrlMsg();
sendMsg->send_id = QHostAddress(ui->combox_tcpip->currentText()).toIPv4Address();
sendMsg->msg_type = 0x10;
sendMsg->conn_type = UDPCONNECTION;
sendMsg->len = headLength;
sendMsg->check_sum = sendMsg->send_id + sendMsg->msg_type + sendMsg->conn_type;
QByteArray str;
str.append((char*)sendMsg, headLength);
//headLength = sizeof(DispCtrlMsg)- sizeof(char*)
//不发送char*部分的数据。
udpSocket->writeDatagram(str, QHostAddress::Broadcast, targetPort);
delete sendMsg;
}
接收
- 接收端需要绑定端口,接受广播包。绑定端口后,如果有广播包,或者udp连接会发送对应的信号。onUDPReadyRead()的触发信号为:readyRead()(该信号继承自QIODevice)。
quint16 port = 6000;
udpSocket->bind(port);
接收
void Widget::onUDPReadyRead()
{
while (udpSocket->hasPendingDatagrams()) {
QHostAddress peerAddr;
quint16 peerPort;
QByteArray recvMsg;
DispCtrlMsg msgHead;
udpSocket->readDatagram((char*)&msgHead, sizeof(msgHead));
qDebug() << QString::number(msgHead.msg_type,16).toUpper();
qDebug() << msgHead.send_id;
serverIP = msgHead.send_id;
onConnected();
}
}