下面是一个简单的QT5下的udp通信的下例子。服务器不停的利用定时器来向socket发送广播消息,客户端可以接收该消息并显示。
首先建立工程UdpServer.pro。建立各控件的布局。
udpserver.h:
class UdpServer:public QDialog
{
Q_OBJECT
public:
UdpServer(QWidget *parent=0,Qt::WindowFlags f=0);
~UdpServer();
prvate:
QLabel *TimerLabel;
QLineEdit *TextLineEdit;
QPushButton *StartBtn;
QVBoxLayout *mainLayout;
};
udpserver.cpp
UdpServer::UdpServer(QWidget *parent,Qt::WindowFlags f):QDialog(parent,f)
{
setWindowTitle(tr("UDP 服务器"));
TimerLabel = new QLabel(tr("Timer:),this);
TextLineEdit = new QLineEdit(this);
StartBtn = new QPushButton(tr("Start"),this);
mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(TimerLabel);
mainLayout->addWidget(TextLineEdit);
mainLayout->addWidget(StartBtn);
}
下面实现服务器的消息广播功能:
在UdpServer.pro 中加入 :
QT += network
这样就可以支持网络开发了。
在udpserver.h中添加想要的槽函数
public slots: