您的位置:首页 > 其它

QUdpSocket实现简单通信

2017-07-28 16:15 489 查看
利用QUdpSocket实现简单的UDP通信功能,需要添加Network模块,.cpp文件代码:

#include "QtGuiApplication1.h"
#include

QtGuiApplication1::QtGuiApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);

udpSocket = new QUdpSocket(this);
udpSocket->bind(8000, QUdpSocket::DefaultForPlatform);//默认模式绑定8000端口
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(OnReadyReadMsg()));
}

//接收数据槽函数
void QtGuiApplication1::OnReadyReadMsg()
{
while (udpSocket->hasPendingDatagrams())//缓冲区有数据等待被读取
{
int size = udpSocket->pendingDatagramSize();
char* pBuffer = new char[size+1];//分配报文大小的内存
memset(pBuffer, 0, size + 1);
udpSocket->readDatagram(pBuffer, size);
/*
开始处理数据
*/
}
}

//发送数据到本机8001端口
void QtGuiApplication1::SendMsg(const char* pData,int length)
{
QHostAddress address = QHostAddress("127.0.0.1");//本机地址
quint16 port = 8001;//发送端口
udpSocket->writeDatagram(pData, length,address, port);//将data中的数据发送
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: