(1)在“UdpServer.pro”中添加如下语句:
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
class UdpServer : public QDialog
{
Q_OBJECT
public:
UdpServer(QWidget *parent = 0 ,Qt::WindowFlags f=0);
~UdpServer();
private:
QLabel *TimerLabel;
QLineEdit *TextLineEdit;
QPushButton *StartBtn;
QVBoxLayout *mainLayout;
};
(2)源文件“udpserver.cpp”的具体代码如下:
#include "udpserver.h"
UdpServer::UdpServer(QWidget *parent , Qt::WindowFlags f)
: QDialog(parent,f)
{
setWindowTitle(tr("UDP Server"));
TimerLabel = new QLabel(tr("计时器:"),this);
TextLineEdit = new QLineEdit(this);
StartBtn = new QPushButton(tr("开始"),this);
mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(TimerLabel);
mainLayout->addWidget(TextLineEdit);
mainLayout->addWidget(StartBtn);
}
(3)服务器界面运行外观如图所示。
(1)在“UdpServer.pro”中添加如下语句:
QT += network
(2)在头文件“udpserver.h”中添加需要的槽函数,其具体代码如下:
#include <QUdpSocket>
#include <QTimer>
public slots:
void StartBtnClicked();
void timeout();
private:
int port;
bool isStarted;
QUdpSocket *udpSocket;
QTimer *timer;
(3)在源文件“udpserver.cpp”中添加声明:
#include <QHostAddress>
StartBtnClicked()函数的具体代码如下:
void UdpServer::StartBtnClicked()
{
if(!isStarted)
{
StartBtn->setText(tr("停止"));
timer->start(1000);
isStarted =true;
}
else
{
StartBtn->setText(tr("开始"));
isStarted = false;
timer->stop();
}
}
timeout()函数完成了向端口发送广播信息的功能,其具体代码如下:
void UdpServer::timeout()
{
QString msg = TextLineEdit->text();
int length=0;
if(msg=="")
{
return;
}
if((length=udpSocket->writeDatagram(msg.toLatin1(),
msg.length(),QHostAddress::Broadcast,port))!=msg.length())
{
return;
}
}
(1)在头文件“udpclient.h”中声明了需要的各种控件,其具体代码如下:
#include <QDialog>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
class UdpClient : public QDialog
{
Q_OBJECT
public:
UdpClient(QWidget *parent = 0 ,Qt::WindowFlags f=0);
~UdpClient();
private:
QTextEdit *ReceiveTextEdit;
QPushButton *CloseBtn;
QVBoxLayout *mainLayout;
};
(2)源文件“udpclient.cpp”的具体代码如下:
#include "udpclient.h"
UdpClient::UdpClient(QWidget *parent , Qt::WindowFlags f)
: QDialog(parent,f)
{
setWindowTitle(tr("UDP Client"));
ReceiveTextEdit = new QTextEdit(this);
CloseBtn = new QPushButton(tr("Close"),this);
mainLayout=new QVBoxLayout(this);
mainLayout->addWidget(ReceiveTextEdit);
mainLayout->addWidget(CloseBtn);
}
(3)客户端界面运行外观如图所示