以下是一个简单的基于Qt的UDP消息收发示例:
#include <QtGui>
#include <QtNetwork>
class UdpSender : public QWidget
{
Q_OBJECT
public:
UdpSender(QWidget *parent = 0);
private slots:
void sendMessage();
private:
QLabel *statusLabel;
QPushButton *sendButton;
QLineEdit *messageLineEdit;
QUdpSocket *udpSocket;
};
UdpSender::UdpSender(QWidget *parent)
: QWidget(parent)
{
setWindowTitle(tr("UDP Sender"));
statusLabel = new QLabel(tr("Ready to send messages."));
sendButton = new QPushButton(tr("&Send"));
messageLineEdit = new QLineEdit;
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(statusLabel);
layout->addWidget(messageLineEdit);
layout->addWidget(sendButton);
setLayout(layout);
udpSocket = new QUdpSocket(this);
connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
}
void UdpSender::sendMessage()
{
QByteArray data;
data.append(messageLineEdit->text());
udpSocket->writeDatagram(data, QHostAddress::LocalHost, 12345);
statusLabel->setText(tr("Sent message: %1").arg(messageLineEdit->text()));
messageLineEdit->clear();
}
class UdpReceiver : public QDialog
{
Q_OBJECT
public:
UdpReceiver(QWidget *parent = 0);
private slots:
void processPendingDatagrams();
private:
QLabel *statusLabel;
QUdpSocket *udpSocket;
};
UdpReceiver::UdpReceiver(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("UDP Receiver"));
statusLabel = new QLabel(tr("Ready to receive messages."));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(statusLabel);
setLayout(layout);
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 12345);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
}
void UdpReceiver::processPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
statusLabel->setText(tr("Received message: %1").arg(QString(datagram)));
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
UdpSender sender;
UdpReceiver receiver;
receiver.show();
sender.show();
return app.exec();
}
#include "main.moc"
这个示例程序包括一个UDP消息发送器和一个UDP消息接收器。当发送器发送一条消息时,接收器会显示该消息的文本内容。在这个示例中,我们使用本地主机地址和端口号12345来进行通信。如果您希望实现更复杂的功能(例如通过网络连接到其他计算机),则需要相应地修改代码。